-
class MainViewController: UIViewController {
-
-
let disposeBag =
DisposeBag()
-
var timeStr:
String? =
"点击发送" {
-
didSet {
-
if timeStr ==
"重新发送" {
-
self.timeButton.setTitle(timeStr,
for: .normal)
-
self.timeButton.setTitleColor(
UIColor.black,
for: .normal)
-
self.timeButton.isEnabled =
true
-
}
else {
-
self.timeButton.setTitle(timeStr,
for: .normal)
-
self.timeButton.setTitleColor(
UIColor.lightGray,
for: .normal)
-
self.timeButton.isEnabled =
false
-
}
-
}
-
}
-
var countdown:
Int =
60 {
-
didSet {
-
timeStr =
String(format:
"%d秒后重发", countdown)
-
}
-
}
-
override
func viewDidLoad() {
-
super.viewDidLoad()
-
self.view.backgroundColor = .white
-
-
view.addSubview(timeButton)
-
timeButton.snp.makeConstraints { (make)
in
-
make.width.equalTo(
100)
-
make.height.equalTo(
40)
-
make.center.equalTo(view.snp.center)
-
}
-
// Do any additional setup after loading the view.
-
}
-
-
func countdownTimer(second: Int, immeiately: Bool = true, duration: ((Int) ->
Void)?) ->
Single<
Void> {
-
guard second >
0
else {
return
Single<
Void>.just(())}
-
if immeiately {
-
duration?(second)
-
}
-
return
Observable<
Int>.interval(
RxTimeInterval.seconds(
1), scheduler:
MainScheduler.instance)
-
.
map{ second-(immeiately ? ($
0 +
1) : $
0) }
-
.take(second+(immeiately ?
0 :
1))
-
.
do(onNext: { (index)
in
-
duration?(index)
-
})
-
.
filter{
return $
0 ==
0 }
-
.
map{
_
in
return () }
-
.asSingle()
-
}
-
-
@objc
func clickButton() {
-
countdownTimer(second:
60) {[
weak
self] (index)
in
-
guard
let
self =
self
else {
return }
-
self.countdown = index
-
debugPrint(
"倒计时: \(index)")
-
}.subscribe {[
weak
self] ()
in
-
guard
let
self =
self
else {
return }
-
self.timeStr =
"重新发送"
-
debugPrint(
"倒计时结束")
-
} onFailure: { (error)
in
-
debugPrint(
"倒计时错误:\(error)")
-
}.disposed(by: disposeBag)
-
}
-
-
lazy
var timeButton:
UIButton = {
-
let button =
UIButton(type: .custom)
-
button.setTitle(
self.timeStr,
for: .normal)
-
button.setTitleColor(
UIColor.black,
for: .normal)
-
button.addTarget(
self, action: #selector(clickButton),
for: .touchUpInside)
-
return button
-
}()
-
-
}
转载:https://blog.csdn.net/wangtianya125/article/details/115633618
查看评论