Reputation: 4330
I have to enable a button based on the characters count on two textfields using 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
}
Finally i acomplish by doing this, but i'm not sure if its the best way:
_ = 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
}
Edit final version:
_ = 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)
Upvotes: 8
Views: 14669
Reputation: 4075
In RxSwift Latest
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)
Upvotes: 3
Reputation: 487
If I understood you correctly, You probably want something like this
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)
For more details I suggest you to look at RxExamples
There you can find a lot of answers to the common problems. Have fun =)
Upvotes: 21