既然是基于RxSwift,首先需要导入第三方库RxSwift,RxCocoa
extension Reactive where Base: UIButton {
/*
button isEnable与否的两种情况下对应的 backgroudColor
*/
public var isEnabledBgColor: UIBindingObserver<Base, Bool> {
return UIBindingObserver(UIElement: self.base) { control, value in
control.backgroundColor = value ? UIColor.blue : UIColor.white
}
}
/*
button isEnable与否的两种情况下对应的 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
}
}
}
以下举例如何调用
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)
}