This code does not work, meaning onChange is never called and the variable is not changed when a dropdown option is selected.
struct ExamplePicker: View {
@State var val: Int32 = 2
var body: some View {
HStack {
Menu {
Picker(selection: $val, label: EmptyView()) {
Text("Val1").tag(1)
Text("Val2").tag(2)
Text("Val3").tag(3)
}
} label: {
HStack {
Text("Value: ")
Spacer()
Text(String(format: "%d", val))
Spacer()
}
}
.onChange(of: val) { newSelection in
print(">>> HERE")
}
}
}
}
but if you change val to type Int it works perfectly fine. This looks like a bug to me
EDIT: Solved - the problem is that in .tag() you need the EXACT same type. so .tag(1) would be Int not Int32. and thus .tag(Int32(1)) is needed
just to make it more confusing, this works:
struct ExamplePicker: View {
@Binding var val: Int64
var body: some View {
HStack {
Picker(selection: $val, label: EmptyView()) {
Text("Val1").tag(1)
Text("Val2").tag(2)
Text("Val3").tag(3)
}
.onChange(of: val) { newSelection in
print(">>> HERE")
}
}
}
}
It works fine when the tag
values of the Picker
items have the same type as the state variable. Like this:
Picker(selection: $val, label: EmptyView()) {
Text("Val1").tag(Int32(1))
Text("Val2").tag(Int32(2))
Text("Val3").tag(Int32(3))
}