首先在项目中进入RxCocoa 和RxSwift
import RxCocoa
import RxSwift
声明需要的属性
let disposed = DisposeBag()
let timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
let countDownStopped = Variable(true)
let leftTime = Variable(Int(30))
懒加载button和label,之后再加载view的时候先使lable隐藏,button展示
leftLabel.isHidden = true
barBtn.isHidden = false
view.addSubview(barBtn)
view.addSubview(leftLabel)
这里就是最重要的方法,在点击button的时候调用这个方法就实现了
func startClicked() {
leftLabel.isHidden = false
barBtn.isHidden = true
self.countDownStopped.value = false
timer.takeUntil(countDownStopped.asObservable().filter{$0})
.subscribe(onNext: { [weak self](event) in
self!.leftTime.value -= 1
print("这里是剩余的时间:\(self?.leftTime.value ?? 0)")
self?.leftLabel.text = "这里是剩余的时间:\(self?.leftTime.value ?? 0)秒"
if (self!.leftTime.value == 0) {
print("倒计时结束")
self!.countDownStopped.value = true
self!.leftTime.value = 30
self!.leftLabel.isHidden = true
self!.barBtn.isHidden = false
self?.leftLabel.text = "这里是剩余的时间:\(self?.leftTime.value ?? 0)秒"
}
}, onError: { (error) in
}).disposed(by: disposed)
}
网友评论