我必须使用Rx
Swift根据两个文本字段上的字符数启用一个按钮
@IBOutlet weak var userTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var buttonToEnabledisable: UIButton! var enabledobservable = combineLatest(userTextField.rx_text,passwordTextField.rx_text) { (user,password) in self.loginButton.enabled = a.characters.count > 0 && b.characters.count > 0 }
最后我通过这样做来完成,但我不确定它是否是最好的方式:
_ = combineLatest(emailTextField.rx_text,passwordTextField.rx_text) { (a: String,b:String) in self.loginButton.enabled = (a.characters.count > 0 && b.characters.count > 0) }.subscribeNext { (result) -> Void in }
编辑最终版本:
_ = combineLatest(emailTextField.rx_text,b:String) in return (a.characters.count > 0 && b.characters.count > 0) }.subscribeNext { enabled in self.loginButton.alpha = enabled ? 1 : 0.5 self.loginButton.enabled = enabled } .adddisposableto(disposeBag)
如果我理解正确,你可能想要这样的东西
let loginValidation = loginTextFiled .rx_text .map({!$0.isEmpty}) .shareReplay(1) let userNameValidation = passwordTextField .rx_text .map({!$0.isEmpty}) .shareReplay(1) let enableButton = combineLatest(loginValidation,userNameValidation) { (login,name) in return login && name } enableButton .bindTo(loginButton.rx_enabled) .adddisposableto(disposeBag)
有关详细信息,我建议您查看RxExamples
在那里你可以找到很多常见问题的答案.玩得开心=)