IOS 定时器封装--倒的正的都可以(Swift版)

最近项目中用到了不少定时器,不管是订单确认、订单支付以及验证码等都会用到倒计时,所以就重新的封装了一个比较好用的,方便使用。天生愚钝的我可能写的没有那么完美,希望各位大神看后能给出指导的建议,包括有什么新的需求可以添加的,我好加以修改。

说多了都是废话,直接上图,你能用到并且能够看上才是真理。
Timer.gif

下面我来简单的说一下如何使用这个定时器:

1.0 创建

@objc enum TYCountDownLabelType: Int {
    case defaultType // 倒计时
    case incrementTimeType // 递增时间
}
// 方式一
let timerL = TYTimerLabel(label: timerLabel) // 默认倒计时
// 方式二 
let timerL = TYTimerLabel(label: timerLabel, type: .defaultType) // .defaultType为倒计时
// 方式三
let timerL = TYTimerLabel(frame: .zero, label: timerLabel, type: .incrementTimeType) // .incrementTimeType递增时间

2.0 属性

    // 是否开始倒计时
    var counting: Bool = false
    // 倒计时结束是否重置时间
    var isResetTime: Bool = false
    // 时间格式类型
    fileprivate var _timeFormat: String?
    var timeFormat: String? {
        get {
            if _timeFormat == nil || (_timeFormat?.count ?? 0) == 0 {
                _timeFormat = defaultTimeFormatter
            }
            return _timeFormat
        } set {
            _timeFormat = newValue
            self.dateFormatter?.dateFormat = _timeFormat
            self.renewalLabel()
        }
    }
    // dateFormatter
    fileprivate var _dateFormatter: DateFormatter?
    fileprivate var dateFormatter: DateFormatter? {
        get {
            if _dateFormatter == nil {
                
                _dateFormatter = DateFormatter.init()
                /**
                 **不同地区有不同的日期格式。使用这个方法的目的:得到指定地区指定日期字段的一个合适的格式
                 **en_US(United States) : MM/dd/YYYY, HH:mm:ss;  en_GB(United Kingdom): dd/MM/YYYY, HH:mm:ss;  zh_CN(中国): YYYY/MM/dd HH:mm:ss
                 **/
                _dateFormatter?.locale = Locale(identifier: "en_GB")
                /**
                 **时区:  任何时区都以GMT为准
                 ** iOS中的时间类NSDate所获取到的时间, 都是相对于GMT的
                 **/
                _dateFormatter?.timeZone = TimeZone(identifier: "GMT")
                _dateFormatter?.dateFormat = self.timeFormat
            }
            return _dateFormatter
        } set {
            _dateFormatter = newValue
        }
    }

3.0 方法

// 开启定时器
timerL.start() 
// 暂停定时器
timerL.pause() 
// 重置定时器
timerL.reset()
// 通过传入时间间隔来设定倒计时的具体时间
timerL.countDownTimeWithTimeInterval(timeInterval: 60) // 设计倒计时一分钟
// 通过传入的Date来设定倒计时的具体时间
timerL.countDownTimeWithDate(date: dateTime ?? Date())
// 通过传入的时间间隔设置递增时间的初始时间,默认是0:0:0
timerL.incrementTimeWithTimeInterval(interval: 60) // 从一分钟开始 
// 获取已经过去的时间
let consumeTime = timerL.etConsumeTime()
// 获取剩余的倒计时时间
let countDownResidueTime = timerL.residueTime()
// 获取倒计时的总时间
let countDownTime = timerL.getCountDownTime()

3.0 代理

/// 自定义代理

@objc protocol TYCountDownLabelTypeDelegate: NSObjectProtocol {
    /**
     ** 方法: 根据参数的判断, 更改label的样式等(根据自己的需求)
     ** 参数label: 用来展示定时器输出文字的label
     ** 参数time: 对于倒计时来说就是当前剩余的时间间隔, 对于递增时间来说就是当前增加到的时间间隔
     **/
    @objc optional func changeTimerLabelAttrAtTime(label: UILabel, time: TimeInterval, type: TYCountDownLabelType)
    
    /**
     ** 方法: 自定义label文字的输出格式
     ** 参数label: 用来展示定时器输出文字的label
     ** 参数time: 对于倒计时来说就是当前剩余的时间间隔, 对于递增时间来说就是当前增加到的时间间隔
     ** 返回值: 自定义的字符串
    **/
    @objc optional func customTextToDisplayAtTime(label: UILabel, time: TimeInterval) -> String?
    /**
     ** 方法: 自定义label文字的输出格式
     ** 参数label: 用来展示定时器输出文字的label
     ** 参数time: 倒计时的总时间间隔
     **/
    @objc optional func countDownTimeOver(label: UILabel, time: TimeInterval)
}

使用起来也是非常的方便,你可以根据你们产品的具体的需求来自定义定时器的样式,根据后台给你们返回的数据的类型来具体的使用。我写一个简单的使用例子:

a. 创建定时器
    //    MARK: 创建定时器Label
    func createTimerLabel() {
        let dateFormatter = DateFormatter()
        let time = "2018-11-29 12:32:25" // 这里自定义
        dateFormatter.dateFormat = "yyy-MM-dd HH:mm:ss"
        let dateTime = dateFormatter.date(from: time)
        
        timer = TYTimerLabel.init(label: timerLabel, type: .defaultType)
        timer?.countDownTimeWithDate(date: dateTime ?? Date())
//        timer?.countDownTimeWithTimeInterval(timeInterval: 60)
        timer?.timeFormat = "HH:mm:ss"
        timer?.isResetTime = true
        timer?.delegate = self
        
        incrementTimer = TYTimerLabel.init(label: incrementTimerLabel, type: .incrementTimeType)
        incrementTimer?.incrementTimeWithTimeInterval(interval: 0)
        incrementTimer?.timeFormat = "HH:mm:ss SS"
        incrementTimer?.delegate = self
    }
b. 开始、暂停、重置按钮的实现(不需要按钮的话直接start()开启)
    //    MARK: 开启定时器
    @objc private func startBtnAction(btn: UIButton) {
        if btn.tag == 1 {
            timer?.start()
        } else {
            incrementTimer?.start()
        }
    }
    //    MARK: 暂停定时器
    @objc private func stopBtnAction(btn: UIButton) {
        if btn.tag == 2 {
            timer?.pause()
        } else {
            incrementTimer?.pause()
        }
    }
    //    MARK: 重置定时器
    @objc private func resetBtnAction(btn: UIButton) {
        if btn.tag == 3 {
            timer?.reset()
        } else {
            incrementTimer?.reset()
        }
    }
c.代理方法的实现(产品有特殊的需求)
extension TYTimerViewController: TYCountDownLabelTypeDelegate {
    //    MARK: 自定义label的样式
    func changeTimerLabelAttrAtTime(label: UILabel, time: TimeInterval, type: TYCountDownLabelType) {
        if label == timerLabel {
            if time < 55 {
                label.textColor = .red
            } else {
                label.textColor = .white
            }
        }
    }
    //    MARK: 自定义文字输出内容
    func customTextToDisplayAtTime(label: UILabel, time: TimeInterval) -> String? {
        if type == "custom" {
            let hours = Int(time / 3600)
            let minutes = Int((time - Double(hours * 3600)) / 60)
            let seconds = Int(time - Double(hours * 3600) - Double(minutes * 60))
            return "\(hours)" + "h" + "\(minutes)" + "min" + "\(  seconds)" + "s"
        } else {
            return nil
        }
    }
    //    MARK: 倒计时结束
    func countDownTimeOver(label: UILabel, time: TimeInterval) {
        label.text = "game over"
    }
}
屏幕快照 2018-11-29 下午3.25.18.png
屏幕快照 2018-11-29 下午3.26.24.png
使用只需要把TYTimerLabel.swift拖入自己的项目即可。如有不足,欢迎指正。

Demo地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,033评论 3 119
  • 那天的天空 正如你的脸庞 清澈透明 在微风的拂动下 河边的垂柳 和你一起 美丽了我的心
    中正恩泽阅读 264评论 6 6
  • 涂磊犀利的一段话,值得思索:“太善良,得不到幸福,反会得到背叛!太现实,体会不到幸福,但不会太受伤!谁更悲哀...
    肥兜er阅读 228评论 0 0
  • 家是心灵的港湾,人生的驿站;是感情的归宿,灵魂的延续! 好长时间不回老家了,很是想念!虽然离得不远,但是带着孩子也...
    成丽crystal阅读 966评论 2 4