I'm trying to trigger an action with a toggle switch. In this case the print message "value did change" doesn't show up on console after clicking on the toggle.
This is targeted for a macOS 10.15 app, .onChange will not work.
struct ContentView: View {
@State private var isToggle : Bool = false {
didSet {
print("value did change")
}
}
var body: some View {
Toggle(isOn: self.$isToggle){
Text("Toggle Label ")
}
}
}
I am going to shamelessly steal the first part of @Asperi's answer, but the second part is mine...
There are two Binding extensions to use from iOS 13, watchOS 6 and macOS 10. The first
.onUpdate()fires when the binding value changes, but does not give you access to the old or new values. It is JUST for side effects. I used this one above simply because theprint()did not need any other value.If you need to use the newValue in your closure, use
.updated. It works very similarly to.onChange(of:)except it modifies the Binding and does not give you access to the old value.