既然是基于RxSwift旱易,首先需要導(dǎo)入第三方庫(kù)RxSwift,RxCocoa
extension Reactive where Base: UIButton {
/*
button isEnable與否的兩種情況下對(duì)應(yīng)的 backgroudColor
*/
public var isEnabledBgColor: UIBindingObserver<Base, Bool> {
return UIBindingObserver(UIElement: self.base) { control, value in
control.backgroundColor = value ? UIColor.blue : UIColor.white
}
}
/*
button isEnable與否的兩種情況下對(duì)應(yīng)的 borderColor
*/
public var isEnabledBorderColor: UIBindingObserver<Base, Bool> {
return UIBindingObserver(UIElement: self.base) { control, value in
control.layer.borderColor = value ? UIColor.blue.cgColor : UIColor.white.cgColor
control.layer.masksToBounds = true
}
}
}
以下舉例如何調(diào)用
class RegisterViewController: UIViewController {
@IBOutlet weak var phoneTextField: UITextField!
@IBOutlet weak var authTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var showBt: UIButton!
@IBOutlet weak var nextBt: UIButton!
@IBOutlet weak var authBt: UIButton!
var isCountDown = false
override func viewDidLoad() {
super.viewDidLoad()
let phoneValid = phoneTextField.rx.text.orEmpty
.map{$0.count >= 11}
.shareReplay(1)
let borderValid = phoneTextField.rx.text.orEmpty
.map{$0.count >= 11 && !(self.isCountDown)}
.shareReplay(1)
borderValid
.bind(to: authBt.rx.isEnabled)
.disposed(by: disposeBag)
borderValid
.bind(to: authBt.rx.isEnabledBorderColor)
.disposed(by: disposeBag)
phoneValid
.bind(to: authBt.rx.isEnabledBgColor)
.disposed(by: disposeBag)
}