There are now two new onChange(of:initial:_:)
's, one with zero closure parameters and one with two.
Both now also provide the option to opt-in to running the code block when the view initially appears, by using initial: true
(false
by default). The former with zero closure parameters is now the new "default" for when you just want to get the new value. The latter with two closure parameters lets you get the old & new value to compare, similar to how we used to do a capture group to get the old value.
iOS 17.0+
struct ContentView: View {
@State private var isLightOn = false
var body: some View {
Toggle("Light", isOn: $isLightOn)
.onChange(of: isLightOn) {
if isLightOn {
print("Light is now on!")
} else {
print("Light is now off.")
}
}
}
}
iOS 14.0+
You can use the onChange(of:perform:)
modifier, like so:
struct ContentView: View {
@State private var isLightOn = false
var body: some View {
Toggle("Light", isOn: $isLightOn)
.onChange(of: isLightOn) { value in
if value {
print("Light is now on!")
} else {
print("Light is now off.")
}
}
}
}
iOS 13.0+
The following as an extension of Binding
, so you can execute a closure whenever the value changes.
extension Binding {
/// When the `Binding`'s `wrappedValue` changes, the given closure is executed.
/// - Parameter closure: Chunk of code to execute whenever the value changes.
/// - Returns: New `Binding`.
func onUpdate(_ closure: @escaping () -> Void) -> Binding<Value> {
Binding(get: {
wrappedValue
}, set: { newValue in
wrappedValue = newValue
closure()
})
}
}
Used like so for example:
struct ContentView: View {
@State private var isLightOn = false
var body: some View {
Toggle("Light", isOn: $isLightOn.onUpdate(printInfo))
}
private func printInfo() {
if isLightOn {
print("Light is now on!")
} else {
print("Light is now off.")
}
}
}
This example doesn't need to use a separate function. You only need a closure.
func
with aprint
in it, even set a breakpoint, and no luck. Yet, when I put SwiftUI code (like creating aText("got here")
it worked. Keeping in mid it's all beta 1, I'm thinking this will be corrected (or at least better documented) in a later beta. – Botvinnik@Published
decorator and subscribe to it. – Covered