RXSwift 實現(xiàn)倒計時按鈕

RXSwift實現(xiàn)

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 ? "發(fā)送驗證碼":"再次發(fā)送(\($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)
    }
 }

喜歡就請點個贊~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容