RxSwift之路02-----RxSwift使用方式

上篇学习了一下,简单的Rx使用的方式,这篇将更直接的使用RxSwift来写一些就简单的UI上的逻辑处理
使用下面代码即可实现一个检测用户名和密码的并作出相应处理的UI逻辑

演示效果

RxSwift之路02-----RxSwift使用方式_第1张图片

**示例代码如下**
import RxSwift
import RxCocoa

class ExampleViewController: UIViewController {
    let disposeBag = DisposeBag()
    let minimalUsernameLength = 5
    @IBOutlet weak var UserName: UILabel!
    @IBOutlet weak var NameTextField: UITextField!
    @IBOutlet weak var NameAlert: UILabel!
    @IBOutlet weak var passward: UILabel!
    @IBOutlet weak var PassWardTextField: UITextField!
    @IBOutlet weak var passWardAlert: UILabel!
    @IBOutlet weak var LoginButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        let userNameValid = NameTextField.rx.text.orEmpty
            .map { $0.count >= self.minimalUsernameLength }
            .share(replay: 1, scope: SubjectLifetimeScope.forever)

        let passwordValid = PassWardTextField.rx.text.orEmpty
            .map { $0.count >= self.minimalUsernameLength }
            .share(replay: 1, scope: SubjectLifetimeScope.forever)

        let evertything = Observable.combineLatest(
        userNameValid,
        passwordValid
        ){$0 && $1}
        .share(replay: 1, scope: SubjectLifetimeScope.forever)


        userNameValid
        .bind(to: PassWardTextField.rx.isEnabled)
        .disposed(by: disposeBag)

        userNameValid
        .bind(to: NameAlert.rx.isHidden)
        .disposed(by: disposeBag)


        passwordValid
        .bind(to: passWardAlert.rx.isHidden)
        .disposed(by: disposeBag)

        evertything
        .bind(to: LoginButton.rx.isEnabled)
        .disposed(by:disposeBag)

            LoginButton.rx.tap
            .subscribe(onNext: {
                self.showAlert()
            })
            .disposed(by: disposeBag)

    }

    func showAlert() {
        let alertView = UIAlertView(
            title: "RxExample",
            message: "This is wonderful",
            delegate: nil,
            cancelButtonTitle: "OK"
        )

        alertView.show()
    }

}

用以上代码即可实现,大大简化了代码

你可能感兴趣的:(RxSwift)