小言_互联网的博客

RxSwift 倒计时按钮

403人阅读  评论(0)

  
  1. class MainViewController: UIViewController {
  2. let disposeBag = DisposeBag()
  3. var timeStr: String? = "点击发送" {
  4. didSet {
  5. if timeStr == "重新发送" {
  6. self.timeButton.setTitle(timeStr, for: .normal)
  7. self.timeButton.setTitleColor( UIColor.black, for: .normal)
  8. self.timeButton.isEnabled = true
  9. } else {
  10. self.timeButton.setTitle(timeStr, for: .normal)
  11. self.timeButton.setTitleColor( UIColor.lightGray, for: .normal)
  12. self.timeButton.isEnabled = false
  13. }
  14. }
  15. }
  16. var countdown: Int = 60 {
  17. didSet {
  18. timeStr = String(format: "%d秒后重发", countdown)
  19. }
  20. }
  21. override func viewDidLoad() {
  22. super.viewDidLoad()
  23. self.view.backgroundColor = .white
  24. view.addSubview(timeButton)
  25. timeButton.snp.makeConstraints { (make) in
  26. make.width.equalTo( 100)
  27. make.height.equalTo( 40)
  28. make.center.equalTo(view.snp.center)
  29. }
  30. // Do any additional setup after loading the view.
  31. }
  32. func countdownTimer(second: Int, immeiately: Bool = true, duration: ((Int) -> Void)?) -> Single< Void> {
  33. guard second > 0 else { return Single< Void>.just(())}
  34. if immeiately {
  35. duration?(second)
  36. }
  37. return Observable< Int>.interval( RxTimeInterval.seconds( 1), scheduler: MainScheduler.instance)
  38. . map{ second-(immeiately ? ($ 0 + 1) : $ 0) }
  39. .take(second+(immeiately ? 0 : 1))
  40. . do(onNext: { (index) in
  41. duration?(index)
  42. })
  43. . filter{ return $ 0 == 0 }
  44. . map{ _ in return () }
  45. .asSingle()
  46. }
  47. @objc func clickButton() {
  48. countdownTimer(second: 60) {[ weak self] (index) in
  49. guard let self = self else { return }
  50. self.countdown = index
  51. debugPrint( "倒计时: \(index)")
  52. }.subscribe {[ weak self] () in
  53. guard let self = self else { return }
  54. self.timeStr = "重新发送"
  55. debugPrint( "倒计时结束")
  56. } onFailure: { (error) in
  57. debugPrint( "倒计时错误:\(error)")
  58. }.disposed(by: disposeBag)
  59. }
  60. lazy var timeButton: UIButton = {
  61. let button = UIButton(type: .custom)
  62. button.setTitle( self.timeStr, for: .normal)
  63. button.setTitleColor( UIColor.black, for: .normal)
  64. button.addTarget( self, action: #selector(clickButton), for: .touchUpInside)
  65. return button
  66. }()
  67. }

 


转载:https://blog.csdn.net/wangtianya125/article/details/115633618
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场