SwiftUI Blog

Mastering SwiftUI: Your Guide to Building Beautiful, Intuitive Apps.

Toggle with text

Do you know the most famous question asked by Italian grandmothers (I miss you, nonne)?

“Have you eaten?”

Imagine answering this question with a simple Yes/No toggle — let’s turn it into a fun widget with a bit of text!

Toggle with text

Take a look at the code:

struct CustomToggleStyle: ToggleStyle {
    var activeColor: Color = .green
    @State var textToggle = "Y"
    
    func makeBody(configuration: Configuration) -> some View {
        HStack {
            configuration.label.font(.largeTitle).foregroundStyle(.pink).bold()
            Spacer()
            RoundedRectangle(cornerRadius: 60)
                .fill(configuration.isOn ? activeColor : Color(.pink))
                .overlay {
                    Circle()
                        .fill(.white)
                        .padding(3)
                        .overlay {
                            Text(textToggle)
                                .foregroundColor(configuration.isOn ? activeColor : Color(.gray))
                        }
                        .offset(x: configuration.isOn ? 15 : -15)
                    
                }
                .frame(width: 80, height: 42)
                .onTapGesture {
                    withAnimation(.spring) {
                        configuration.isOn.toggle()
                        textToggle = configuration.isOn ? "Y" :"N"
                    }
                }
        }
    }
}

We set the active color to green, and the inactive one (if you didn’t eat) to pink. For the label, we chose the same shade of pink.

TheCustomToggleStyle must conform to the ToggleStyle protocol, which requires the implementation of the makeBody function.

The Configuration contains the current state of the Toggle. To modify the label’s properties, we update Configuration.label. For the UI part, we create a RoundedRectangle with a circle overlay that changes position based on the toggle’s state (isOn). We also apply an animation when the toggle is tapped.

The uncommon part is displaying text inside the circle using the Text widget.

Now, let’s see how to use it:

struct ContentView: View {
    @State var eat: Bool = false
    
    var body: some View {
        VStack {
            Toggle(isOn: $eat) {
                Text("Have you eaten?")
            }.toggleStyle(CustomToggleStyle( activeColor: .green))
        }.padding()
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *