简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM