我试图将一个UITextField绑定到一个viewModel,但是无论我做什么,我都会得到Cannot invoke 'bind' with an argument list of type '(to: EmailViewModel)。我做错什么了?
注册视图模型

class SignUpViewModel {

    let model: SignUpModel
    private let disposeBag = DisposeBag()

    let emailFieldViewModel = EmailViewModel()

    init(model :SignUpModel) {
        self.model = model
    }


}

电子邮件视图模型
struct EmailViewModel : FieldViewModel {

    var value: Variable<String> = Variable("")
    var errorValue: Variable<String?> = Variable(nil)

    let title = "Email"
    let errorMessage = "Email is wrong"

    func validate() -> Bool {
        let emailPattern = "[A-Z0-9a-z._%+-]+@([A-Za-z0-9.-]{2,64})+\\.[A-Za-z]{2,64}"
        guard validateString(value.value, pattern:emailPattern) else {
            errorValue.value = errorMessage
            return false
        }
        errorValue.value = nil
        return true
    }
}

视图控制器
class SignUpViewController: UIViewController {

    @IBOutlet var emailField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        configureBinding()

    }

    private func configureBinding() {

        // binding
        self.emailField.rx.text.bind(to: viewModel.emailFieldViewModel)

    }

}

最佳答案

bind函数需要一个符合ObserverType协议的对象。这里,EmailViewModel不符合该类型,因此出现错误。
编写扩展使EmailViewModel符合ObserverType协议可以解决编译错误。

extension EmailViewModel: ObserverType {
  func on(_ event: Event<String?>) {
    switch event {
    case .next(let newValue): value.value = newValue ?? ""
    case .error(_), .completed: fatalError("Completion and error are not handled")
    }
  }
}

10-08 09:28