Home > database >  SwiftUI TextField resets value and ignores binding
SwiftUI TextField resets value and ignores binding

Time:09-24

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()
    }
}

gif showing the textfield resetting

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?).

CodePudding user response:

Here you go!

class ViewModel: ObservableObject {
    @Published var s = "Default String"
}

struct ContentView: View {
    @StateObject private var vm = ViewModel()
    var body: some View {
        TextField("S:", text: $vm.s)
            .padding()
    }
}

For use in multiple views, in every view where you'd like to use the model add:

@EnvironmentObject private var vm: ViewModel 

But don't forget to inject the model to the main view:

ContentView().environmentObject(ViewModel())
  • Related