美文网首页
RXSwift 实现倒计时按钮

RXSwift 实现倒计时按钮

作者: 九龙 | 来源:发表于2018-09-12 17:58 被阅读12次

    RXSwift实现

    import UIKit
    import RxSwift
    import RxCocoa
    
    let countDownSeconds: Int = 60
    
    class ViewController: UIViewController {
    
        let disposeBag = DisposeBag()
        
        @IBOutlet weak var sendCodeButton: UIButton!
        
        override func viewDidLoad() {
            super.viewDidLoad()
      
            let timer = Observable<Int>.timer(0, period: 1, scheduler: MainScheduler.instance)
               .map{countDownSeconds - $0}
               .filter{ $0 >= 0 }
               .asDriver(onErrorJustReturn: 0)
            
            let second = sendCodeButton.rx.tap
                .flatMapLatest { _ -> Driver<Int> in
                    return timer
            }
            let sendCodeButtonText = second.map { $0 == 0 ? "发送验证码":"再次发送(\($0)s)"}
            let sendButtonEnable = second.map{$0 == 0 ? true : false}
            
            sendCodeButtonText
                .bind(to: sendCodeButton.rx.title(for: .normal))
                .disposed(by: disposeBag)
            
            sendButtonEnable
                .bind(to: sendCodeButton.rx.isEnabled)
                .disposed(by: disposeBag)
        }
     }
    

    相关文章

      网友评论

          本文标题:RXSwift 实现倒计时按钮

          本文链接:https://www.haomeiwen.com/subject/qekbgftx.html