swift 用GCD写的倒计时 防止计时器不准

来源:互联网 发布:学淘宝开店 编辑:程序博客网 时间:2024/05/16 08:19

self.timeCount =60


var queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)

                var _timer =dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0,queue)

                

                dispatch_source_set_timer(_timer,dispatch_walltime(nil,0), NSEC_PER_SEC,0)

                dispatch_source_set_event_handler(_timer, { () ->Void in

                    ifself.timeCount <=0 {

                        dispatch_source_cancel(_timer)

                        dispatch_async(dispatch_get_main_queue(), { () ->Void in

                            self.authCodeButton.setTitle("重新获取", forState: UIControlState.Normal)

                            self.authCodeButton.userInteractionEnabled =true

                        })

                    } else {

                        

                        dispatch_async(dispatch_get_main_queue(), { () ->Void in

                            self.authCodeButton.titleLabel?.text = NSString(format: "剩余%d",self.timeCount)

                            self.authCodeButton.setTitle(NSString(format:"剩余%d",self.timeCount), forState:UIControlState.Normal)

                        })

                        self.timeCount--

                    }

                })

                dispatch_resume(_timer)

0 0
原创粉丝点击