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)
}
}
喜歡就請點個贊~