Hi, I have a Picker and I would like to perform action when user changes its value. Here is code:
enum Type {
case Type1, Type2
}
class ViewModel: ObservableObject {
@Published var type = Type.Type1
init() {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.type = Type.Type2
}
}
}
struct ContentView: View {
@ObservedObject var viewModel: ViewModel
var body: some View {
VStack {
Row(type: $viewModel.type) {
self.update()
}
}
}
func update() {
// some update logic that should be called only when user changed value
print("update")
}
}
struct Row: View {
@Binding var type: Type
var action: () -> Void
var body: some View {
Picker("Type", selection: $type) {
Text("Type1").tag(Type.Type1)
Text("Type2").tag(Type.Type2)
}
.onChange(of: type, perform: { newType in
print("changed: \(newType)")
action()
})
}
}
There is a ViewModel which simulates being changed externally. Value that it publishes is bounded to Picker with @Binding. I would like to perform an action (for example an update) when user changes value. I tried to use onChange on binding but the problem is that this event is called also when the value is changed externally and I don't want this. How can I do this?