码迷,mamicode.com
首页 > 编程语言 > 详细

Swift3.0 GCD定时器的使用,实现倒计时,UIDatePicker的使用, 仿写一个活动倒计时的DEMO

时间:2017-02-22 10:26:05      阅读:358      评论:0      收藏:0      [点我收藏+]

标签:ddc   地址   views   async   function   rip   lag   span   string   

直接看主要代码

//截止日期
let endDate = datePicker.date
//开始日期
let startDate = Date()
//时间间隔
let timeInterval:TimeInterval = endDate.timeIntervalSince(startDate)

if timer == nil {
    //剩余时间
    var timeout = timeInterval
    if timeout != 0 {

        //创建全局队列
        let queue = DispatchQueue.global()
        //在全局队列下创建一个时间源
        timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
        //设定循环的间隔是一秒,并且立即开始
        timer?.scheduleRepeating(wallDeadline: DispatchWallTime.now(), interval: .seconds(1))
        //时间源出发事件
        timer?.setEventHandler(handler: {
            //必须是当前日期往后的日期,在datePicker上也做了限制
            if timeout <= 0 {
                self.timer?.cancel()
                self.timer = nil
                DispatchQueue.main.async(execute: {
                    self.day.text = "00"
                    self.hour.text = "00"
                    self.minute.text = "00"
                    self.second.text = "00"
                })
            } else {
                //计算剩余时间
                let days = Int(timeout) / (3600 * 24)
                if days == 0 {
                    self.day.text = ""
                }
                let hours = (Int(timeout) - Int(days) * 24 * 3600) / 3600
                let minutes = (Int(timeout) - Int(days) * 24 * 3600 - Int(hours) * 3600) / 60
                let seconds = Int(timeout) - Int(days) * 24 * 3600 - Int(hours) * 3600 - Int(minutes) * 60
                //主队列中刷新UI
                DispatchQueue.main.async(execute: {
                    if days == 0 {
                        self.day.text = "0"
                    } else {
                        self.day.text = "\(days)"
                    }
                    if hours < 10 {
                        self.hour.text = "0" + "\(hours)"
                    } else {
                        self.hour.text = "\(hours)"
                    }
                    if minutes < 10 {
                        self.minute.text = "0" + "\(minutes)"
                    } else {
                        self.minute.text = "\(minutes)"
                    }
                    if seconds < 10 {
                        self.second.text = "0" + "\(seconds)"
                    } else {
                        self.second.text = "\(seconds)"
                    }
                })
                timeout -= 1
            }
        })
        //启动时间源
        timer?.resume()
    }
}

DEMO效果图

技术分享

DEMO下载地址

Swift3.0 GCD定时器的使用,实现倒计时,UIDatePicker的使用, 仿写一个活动倒计时的DEMO

标签:ddc   地址   views   async   function   rip   lag   span   string   

原文地址:http://blog.csdn.net/feng2qing/article/details/56304809

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!