简体   繁体   English

捆绑<String?>在 SwiftUI 视图文本字段上

[英]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 中绑定 firstname 属性,如下所示:

 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.要绑定对象,您的变量需要符合新包装器@State@Binding@ObservableObject等之一。

Because your RegistrationViewModel doesn't conform to View the only way to do it is to have your RegistrationViewModel conform to ObservableObject .因为您的RegistrationViewModel不符合View唯一的方法是让您的RegistrationViewModel符合ObservableObject

class RegistrationViewModel: ObservableObject {

    @Published var firstname: String?
}

Once that is done you can call it View using完成后,您可以将其称为View使用

@ObservedObject var resgistrationVM: RegistrationViewModel = RegistrationViewModel()

or as an @EnvironmentObject或作为@EnvironmentObject

https://developer.apple.com/tutorials/swiftui/handling-user-input 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 不能很好地处理可选项,但extension可以很容易地处理它。

SwiftUI Optional TextField SwiftUI 可选文本字段

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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