Reputation: 1267
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
Reputation: 12125
Well, you should not name your custom ToggleStyle ToggleStyle
.
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