I want to change some other unrelated @State variable when a Picker gets changed but there is no onChanged and it\'s not possible to p
Here is what I just decided to use... (deployment target iOS 13)
struct MyPicker: View {
@State private var favoriteColor = 0
var body: some View {
Picker(selection: $favoriteColor.onChange(colorChange), label: Text("Color")) {
Text("Red").tag(0)
Text("Green").tag(1)
Text("Blue").tag(2)
}
}
func colorChange(_ tag: Int) {
print("Color tag: \(tag)")
}
}
Using this helper
extension Binding {
func onChange(_ handler: @escaping (Value) -> Void) -> Binding {
return Binding(
get: { self.wrappedValue },
set: { selection in
self.wrappedValue = selection
handler(selection)
})
}
}
EDIT:
If your deployment target is set to iOS 14 or higher -- Apple has provided a built in onChange extension to View, which can be used like this instead (Thanks @Jeremy):
Picker(selection: $favoriteColor, label: Text("Color")) {
// ..
}
.onChange(of: favoriteColor) { print("Color tag: \($0)") }