GCD定时器,以及数字转换成时间格式类型的样式的方法

//    MARK: 显示时间label
private lazy var timeLabel: UILabel = {
    let label = UILabel()
    label.textColor = UIColor.white
    label.font = UIFont.systemFont(ofSize: 20)
    return label
}()

//    MARK: GCD定时器
var timerS: DispatchSourceTimer?
//设定定时时间
var countTime: Int = 0
func setTimerWithGCD()
{
    // 在global线程里创建一个时间源
    self.timerS = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
    // 设定这个时间源是每1.0秒循环一次,立即开始
    timerS?.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.milliseconds(1000))
    // 设定时间源的触发事件
    timerS?.setEventHandler(handler: {
        // 每1秒计时一次
        self.countTime += 1
        // 返回主线程处理一些事件,更新UI等等
        DispatchQueue.main.async {
            self.setTimerStr()
        }
    })
    //启动定时器
    timerS?.activate()
}

var minute: Int = 0
//    MARK: 将int转换成时间格式样式的方法
private func setTimerStr()
{
    if minute == 59 {minute = 0}
    
    if self.countTime > 59
    {
        self.countTime = 0
        minute += 1
    }
    self.timeLabel.text = "\(String.init(format: "%02d", minute)) " + ": " + "\(String.init(format: "%02d", self.countTime))"
    
}
image.png

上面的是正序的时间,下面这个是倒叙的时间

//    MARK: GCD定时器
var timerS: DispatchSourceTimer?
//设定定时时间
var countTime: Int = 60
func setTimerWithGCD()
{
    // 在global线程里创建一个时间源
    self.timerS = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
    // 设定这个时间源是每1.0秒循环一次,立即开始
    timerS?.scheduleRepeating(deadline: .now(), interval: DispatchTimeInterval.milliseconds(1000))
    // 设定时间源的触发事件
    timerS?.setEventHandler(handler: {
        // 每1秒计时一次
        self.countTime -= 1
        // 返回主线程处理一些事件,更新UI等等
        DispatchQueue.main.async {
            self.setTimerStr()
        }
    })

    //启动定时器
    if #available(iOS 10.0, *) {
        timerS?.activate()
    } else {
        timerS?.resume()
    }
}

//表示倒计时总时间
var minute: Int = 14
//    MARK: 将int转换成时间格式样式的方法
private func setTimerStr()
{
    if minute <= 0 && countTime <= 0
    {
        print("时间结束")
        self.timeLabel.text = "00: 00"
        timerS?.cancel()
        // 这里进行发服务,时间变成00之后需要做的事情
        return
    }

    if self.countTime < 0
    {
        self.countTime = 59
        minute -= 1
    }
    self.timeLabel.text = "\(String.init(format: "%02d", minute)) " + ": " + "\(String.init(format: "%02d", self.countTime))"
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容