Swift开发DispatchSourceTimer倒计时

作者: 让代码飞 | 来源:发表于2018-06-01 11:03 被阅读10次

    倒计时是个很常用的东西,创建倒计时要把计时器放入到runloop 当中,因为计时器也是一种资源,资源只有放入到runloop当中才能起作用。创建计时器的方法有好几种:
    1,NSTimer 在swift当中没有NS直接Timer进行创建
    2,CADisplayLink以屏幕刷新帧率结束进行触发计时操作,精准度比较高
    3,DispatchSourceTimer 利用GCD进行创建计时器,系统默认进行重复操作
    因为计时器是这玩意很容易出现线程的问题,而且处理不当会直接影响性能和用户的体验方面,所以推荐使用GCD来创建计时器,这里是以swift为例简单介绍一下。

    倒计时.gif
    创建计时器
    var time = DispatchSource.makeTimerSource()
    //倒计时的总时间 初始值自己填写
     var times = TimeInterval()  
    //repeating代表间隔1秒 
    time.schedule(deadline: .now(), repeating: 1)
            time.setEventHandler(handler: {
                if self.times<0{
                    self.time.cancel()
                }else {
                    DispatchQueue.main.async {
                        self.button.setTitle(self.returnTimeTofammater(times: self.times), for: .normal)
                        self.times-=1
                    }
                }
            })
    
     //点击开始倒计时
        @objc func starAction(sender:UIButton){
            if sender.isSelected == true {
                time.suspend()
                sender.setTitle("暂停", for: .normal)
            }else{
                time.resume()
            }
            sender.isSelected = !sender.isSelected
        }
    
    介绍两个方法,一个是将TimeInterval类型的值转为字符串
     //将多少秒传进去得到00:00:00这种格式
        func returnTimeTofammater(times:TimeInterval) -> String {
            if times==0{
                return "00:00:00"
            }
            var Min = Int(times / 60)
            let second = Int(times.truncatingRemainder(dividingBy: 60));
            var Hour = 0
            if Min>=60 {
                Hour = Int(Min / 60)
                Min = Min - Hour*60
                return String(format: "%02d : %02d : %02d", Hour, Min, second)
            }
            return String(format: "00 : %02d : %02d", Min, second)
        }
    
    一个是将字符串类型的值转为int数字
    //根据显示的字符串00:00:00转化成秒数
        func getSecondsFromTimeStr(timeStr:String) -> Int {
            if timeStr.isEmpty {
                return 0
            }
            let timeArry = timeStr.replacingOccurrences(of: ":", with: ":").components(separatedBy: ":")
            var seconds:Int = 0
            if timeArry.count > 0 && isPurnInt(string: timeArry[0]){
                let hh = Int(timeArry[0])
                if hh! > 0 {
                    seconds += hh!*60*60
                }
            }
            if timeArry.count > 1 && isPurnInt(string: timeArry[1]){
                let mm = Int(timeArry[1])
                if mm! > 0 {
                    seconds += mm!*60
                }
            }
            if timeArry.count > 2 && isPurnInt(string: timeArry[2]){
                let ss = Int(timeArry[2])
                if ss! > 0 {
                    seconds += ss!
                }
            }
            return seconds   
        }
        //扫描字符串的值
        func isPurnInt(string: String) -> Bool {
            let scan:Scanner = Scanner.init(string: string)
            var val:Int = 0
            return scan.scanInt(&val) && scan.isAtEnd
        }
    

    说到这里基本的就完了,自己可以动手试一下

    相关文章

      网友评论

        本文标题:Swift开发DispatchSourceTimer倒计时

        本文链接:https://www.haomeiwen.com/subject/vnphsftx.html