我必须使用RxSwift
启用基于两个文本字段上的字符数的按钮@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, passwordTextField.rx_text) { (a: String, 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)
答案 0 :(得分:15)
如果我理解正确,你可能想要这样的东西
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
在那里你可以找到很多常见问题的答案。 玩得开心=)
答案 1 :(得分:0)
在RxSwift最新版中
let nameValidation = self.userNameTxtFld
.rx.text
.map({!($0?.isEmptyString())!})
.share(replay: 1)
let pwdValidation = passwdTxtFld
.rx.text
.map({!($0?.isEmptyString())!})
.share(replay: 1)
let enableButton = Observable.combineLatest(nameValidation, pwdValidation) { $0 && $1 }
.share(replay: 1)
enableButton
.bind(to: loginBtn.rx.isEnabled)
.disposed(by: disposeBag)