john doe
john doe

Reputation: 9680

Binding<String?> on the SwiftUI View TextField

I have the following view model:

struct RegistrationViewModel {

    var firstname: String?
}

I want to bind the firstname property in the TextField as shown below:

 TextField("First name", text: $registrationVM.firstname)
                      .textFieldStyle(RoundedBorderTextFieldStyle())

I keep getting an error that Binding is not allowed.

Upvotes: 0

Views: 1292

Answers (1)

lorem ipsum
lorem ipsum

Reputation: 29614

To bind objects your variable needs to conform to one of the new wrappers @State, @Binding, @ObservableObject, etc.

Because your RegistrationViewModel doesn't conform to View the only way to do it is to have your RegistrationViewModel conform to ObservableObject.

class RegistrationViewModel: ObservableObject {

    @Published var firstname: String?
}

Once that is done you can call it View using

@ObservedObject var resgistrationVM: RegistrationViewModel = RegistrationViewModel()

or as an @EnvironmentObject

https://developer.apple.com/tutorials/swiftui/handling-user-input

Also, SwiftUI does not work well with optionals but an extension can handle that very easily.

SwiftUI Optional TextField

extension Optional where Wrapped == String {
    var _bound: String? {
        get {
            return self
        }
        set {
            self = newValue
        }
    }
    public var bound: String {
        get {
            return _bound ?? ""
        }
        set {
            _bound = newValue.isEmpty ? nil : newValue
        }
    }
}

Upvotes: 1

Related Questions