感受一份RxSwift的小Demo
用户名大于五个字符隐藏用户名红色提示label,密码输入框可以使用,密码大于6个字符,隐藏密码框下的红色提示label,用户名密码输入框同时满足字符限制,登陆按钮可以使用。
关注重点在disposBag不可以使用DisposeBag()
import UIKit
import RxCocoa
import RxSwift
fileprivate let minUsernameLength = 5
fileprivate let minPasswordLength = 6
class ViewController: UIViewController {
@IBOutlet weak var usernameTextFiled: UITextField!
@IBOutlet weak var usernameValidLabel: UILabel!
@IBOutlet weak var passwordTextFiled: UITextField!
@IBOutlet weak var passwordValidLabel: UILabel!
@IBOutlet weak var loginBtn: UIButton!
var disposeBag = DisposeBag.init()
override func viewDidLoad() {
super.viewDidLoad()
// usernameTextFiled.rx.text序列 - usernameVaild 序列
let usernameVaild = usernameTextFiled.rx.text.orEmpty
.map { (text) -> Bool in
return text.count >= minUsernameLength
}
// 绑定到我们验证显示
usernameVaild.bind(to: usernameValidLabel.rx.isHidden)
.disposed(by: disposeBag)
usernameVaild.bind(to: passwordTextFiled.rx.isEnabled)
.disposed(by: disposeBag)
let passwordVaild = passwordTextFiled.rx.text.orEmpty
.map { (text) -> Bool in
return text.count >= minPasswordLength
}
passwordVaild.bind(to: passwordValidLabel.rx.isHidden)
.disposed(by: disposeBag)
// 决定按钮 - button.rx.isenable
Observable.combineLatest(usernameVaild,passwordVaild) { $0 && $1}
.bind(to: loginBtn.rx.isEnabled)
.disposed(by: disposeBag)
//这里要注意,disposBag不可以用DisposrBag()来代替
//因为DisposrBag()只是一个临时变量,执行一次就被销毁
loginBtn.rx.tap.subscribe(onNext: { () in
print("dianji")
}).disposed(by: disposeBag)
}
}