Is there a way I can use .onChange
to detect the change of multiple @State
properties at once? I know I could just chain 2 .onChange
modifiers but it would be better if I could just detect all at once and run some code.
@State private var width = 0.0
@State private var height = 0.0
var body: some View {
Button(action: {
width += 0.1
}, label: {
Text("Width + 0.1")
})
.onChange(of: width) { _ in
print("Changed")
}
}
2
Answers
For this case here is the simplest I think
Update: as I wrote above is ‘simplest’ (and for specific scenarios can be enough), but of course other variants, "more smart/heavy/generic/etc", are also available.
Thanks to @AgentBilly, here is one of them:
Create a struct and use that as your state:
Then init it as your state: