D'you know? If you just go to bed and sleep for ten hours, the answer comes to you. Here's how to do it:
var newMode: Int = modelData.mode // Get the initial value from the model
struct SettingsView: View {
@EnvironmentObject var modelData: ModelData // Get access to the model data
@State private var mode = newMode // Create a @State var with the initial value
var body: some View {
ScrollView {
SettingsView_Display(mode: $mode) // Send the value to the subview
.onChange(of: modelData.mode) { value in
// When the value in the modelData changes, update mode and newMode. Because mode is a @State var it updates the subview, which redraws it.
mode = value
newMode = value
}
}
}
}
}
struct SettingsView_Display: View {
@Binding var mode: Int // Here's the bound value
var body: some View {
Picker("Mode", selection: $mode) { // Create a picker with the bound value
Text("0").tag(0)
Text("1").tag(1)
Text("2").tag(2)
.pickerStyle(.navigationLink)
.onChange(of: mode) { value in // When the mode is changed by the user using the picker, update the newMode value
newMode = value
}
.onChange(of: modelData.mode) { value in // When the mode is changed here, update the mode and newMode values
mode = value
newMode = value
}
// Not gonna lie, some of that might seem overkill, but it works
}
}
}