Using a TextField on a mac app, when I hit 'return' it resets to its original value, even if the underlying binding value is changed.
import SwiftUI
class ViewModel {
let defaultS = "Default String"
var s = ""
var sBinding: Binding<String> {
.init(get: {
print("Getting binding \(self.s)")
return self.s.count > 0 ? self.s : self.defaultS
}, set: {
print("Setting binding")
self.s = $0
})
}
}
struct ContentView: View {
@State private var vm = ViewModel()
var body: some View {
TextField("S:", text: vm.sBinding)
.padding()
}
}
Why is this? Shouldn't it 'get' the binding value and use that? (i.e. shouldn't I see my print statement "Getting binding" in the console after I hit 'return' on the textfield?).

@Statefor shared values (i.e. sharing it with a ViewModel). If you want to use a ViewModel (or "DataModel" or "Model"), you have to use either a@StateObjector an@ObservedObject. Think of@Stateas a private variable.@Statenow@StateObject. By declaring it as '@StateObject private var vm = ViewModel()` you create a NEWViewModeland do not share one model. This is fine if you only have one view using it, but if you have multiple different views, you are not using a single source of truth for them.