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)
}
}
网友评论