Abhishek
Abhishek

Reputation: 1267

configuration.isOn.toggle() Not working in Custom Toggle in SwiftUI

I have made a screen where I used a custom toggle. But when I am tapping on the toggle button, it's always printing "isOff" because the configuration.toggle value is not updating and is always set to false.

struct TestToggleView: View {
    @Binding private var isOn: Bool

     init(isOn: Binding<Bool>) {
         _isOn = isOn
     }

     public var body: some View {
         Toggle(isOn: $isOn, label: {
             Text("Hi)
         })
         .toggleStyle(ToggleStyle())
     }
}


private struct ButtonToggleStyle: ToggleStyle {


    func makeBody(configuration: Configuration) -> some View {
        HStack(alignment: .center) {
                             configuration.label
                             Text("Yes")
        }.frame(maxWidth: .infinity)
                          .onTapGesture {
                              configuration.isOn.toggle()
                              if configuration.isOn {
                                  print("isOn")
                              } else {
                                  print("isOff")
                          }
                          }
                          .onAppear {
                              print(configuration.isOn)
                   }
           }
    }
}

Upvotes: 2

Views: 615

Answers (1)

ChrisR
ChrisR

Reputation: 12125

  1. Well, you should not name your custom ToggleStyle ToggleStyle.

  2. To change the isOn value you have to go to the wrappedValue: configuration.$isOn.wrappedValue.toggle()

Here is a complete example:

struct ContentView: View {
    
    @State private var isOn = false
    
    var body: some View {
        Toggle(isOn: $isOn, label: {
            Text("Hi") })
            .toggleStyle(MyToggleStyle())
    }
}

struct MyToggleStyle: ToggleStyle {
    
    func makeBody(configuration: Configuration) -> some View {
        HStack(alignment: .center) {
            configuration.label
            Text(configuration.isOn ? "Yes" : "No")
        }.frame(maxWidth: .infinity)
        
            .onTapGesture {
                configuration.$isOn.wrappedValue.toggle()
            }
    }
}

Upvotes: 2

Related Questions