O2CountdownButton.swift 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. //
  2. // O2CountdownButton.swift
  3. // O2Platform
  4. //
  5. // Created by 刘振兴 on 2016/12/16.
  6. // Copyright © 2016年 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. class O2CountdownButton: UIButton {
  10. //定时秒数
  11. var count:Int = 60
  12. //定时器
  13. var timer:Timer!
  14. //标签
  15. var labelTimeS:UILabel!
  16. //默认按钮标题
  17. var normalText = "获取验证码" {
  18. didSet {
  19. self.setTitle(normalText, for: .normal)
  20. self.layoutIfNeeded()
  21. }
  22. }
  23. //是否在定时状态
  24. var timeStatus = false
  25. //标签字颜色
  26. var labelTextColor = UIColor.white
  27. //按钮正常背景色
  28. var normalColor = base_color {
  29. didSet{
  30. if self.isEnabled {
  31. self.backgroundColor = normalColor
  32. self.layoutIfNeeded()
  33. }
  34. }
  35. }
  36. //按钮定时时的背景色
  37. var disableColor = toolbar_text_color {
  38. didSet {
  39. if !self.isEnabled {
  40. self.backgroundColor = disableColor
  41. self.layoutIfNeeded()
  42. }
  43. }
  44. }
  45. override func awakeFromNib() {
  46. super.awakeFromNib()
  47. labelTimeS = UILabel(x: 0, y: 0, w: self.frame.size.width, h: self.frame.size.height)
  48. labelTimeS.textAlignment = .center
  49. labelTimeS.font = UIFont(name: "PingFangSC-Regular", size: 14.0)!
  50. labelTimeS.text = normalText
  51. labelTimeS.textColor = labelTextColor
  52. //self.addSubview(labelTimeS)
  53. self.setTitle(normalText, for: .normal)
  54. self.setTitleColor(UIColor.white, for: .normal)
  55. self.backgroundColor = normalColor
  56. }
  57. public func startCount(){
  58. self.isEnabled = false
  59. self.timeStatus = !self.timeStatus
  60. //把按钮本身标题清空
  61. self.setTitle("", for: .normal)
  62. //开始把Label add Button
  63. labelTimeS.text = "\(self.count)s重新获取"
  64. self.addSubview(labelTimeS)
  65. //设置按钮背景色
  66. self.backgroundColor = disableColor
  67. if timer != nil {
  68. timer.invalidate()
  69. timer = nil
  70. }
  71. timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateLabel), userInfo: nil, repeats: true)
  72. timer.fire()
  73. }
  74. ///停止更新
  75. public func stopCount(){
  76. self.timeStatus = !self.timeStatus
  77. timer.invalidate()
  78. labelTimeS.removeFromSuperview()
  79. self.setTitle(normalText, for: .normal)
  80. count = 60
  81. self.isEnabled = true
  82. self.backgroundColor = normalColor
  83. }
  84. ///每秒更新一次Label
  85. @objc fileprivate func updateLabel(){
  86. count-=1;
  87. if count <= 0 {
  88. self.stopCount()
  89. }else{
  90. labelTimeS.text = "\(self.count)s重新获取"
  91. }
  92. }
  93. }