反应式表单验证 cocoa

Form validation in reactive cocoa

我正在尝试验证具有多个文本字段的表单。但是只有当两个文本字段都被编辑时我才能观察到...

let validUserNameSignal =
    self.nameTextField
        .reactive
        .continuousTextValues
        .skipNil()
        .map({ [=11=].characters.count > 3 })

let pwdPasswordFieldSignal = 
    self.lastnameTextField.reactive
        .continuousTextValues
        .skipNil()
        .map({[=11=].characters.count > 3})

let formValidation =  validUserNameSignal.combineLatest(with: pwdPasswordFieldSignal)

formValidation.observeValues { (userNameResult,pwdResult) in
    print(userNameResult)
    print(pwdResult)
}

我的方法好还是有别的方法?

continuousTextValues是一个Signal,语义很热。这意味着它仅发出观察后发生的变化。

您可能希望将 formValidation 信号变成生产者,并为默认值添加前缀。

SignalProducer(signal: formValidation)
    .map { [=10=] &&  }
    .prefix(value: false)
    .startWithValues { ... }

这是基本 ViewController 的示例实现,我清理了一些我认为可以做得更好的地方。

class ViewController: UIViewController {
    @IBOutlet weak var nameTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!

    func nameValidation(for field: UITextField) -> Signal<Bool, NoError> {
        return field
            .reactive
            .continuousTextValues
            .skipNil()
            .map { [=10=].characters.count > 3 }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let validUserNameSignal = nameValidation(for: nameTextField)
        let lastNameFieldSignal = nameValidation(for: lastNameTextField)
        let formValidation =
            SignalProducer(signal: validUserNameSignal.combineLatest(with: lastNameFieldSignal))
                .map { [=10=] &&  }
                .prefix(value: false)

        formValidation.startWithValues {
            print([=10=])
        }
    }
}