之前只是用过以下两种方式使用计时器。
1、NSTimer 在swift当中没有NS直接Timer进行创建
2、CADisplayLink以屏幕刷新帧率结束进行触发计时操作,精准度比较高
DispatchSourceTimer 利用GCD进行创建计时器,系统默认进行重复操作
因为计时器是这玩意很容易出现线程的问题,而且处理不当会直接影响性能和用户的体验方面,所以推荐使用GCD来创建计时器。
import UIKit
class ViewController: UIViewController {
var timer: DispatchSourceTimer?
var flag: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .custom)
button.backgroundColor = .red
button.frame = CGRect(x: 0, y: 0, width: 100, height: 60)
button.setTitle("确认锅底", for: .normal)
button.setTitleColor(.lightGray, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
button.center = view.center
view.addSubview(button)
timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
timer?.schedule(deadline: .now(), repeating: .seconds(1))
// 设定时间源的触发事件
timer?.setEventHandler(handler: {
DispatchQueue.main.async {
self.flag = !self.flag
button.titleLabel?.font = UIFont.systemFont(ofSize: self.flag ? 14 : 18)
button.backgroundColor = self.flag ? .yellow : .red
button.titleLabel?.backgroundColor = self.flag ? .darkGray : .clear
}
})
// 启动时间源
timer?.resume()
}
}
参考链接:
https://www.jianshu.com/p/67bab7e8f6b2
这个是一朋友给我写的上篇实现的缩放动画实现的闪跳功能,记录一下这个定时器的使用吧。还是动画实现好,定时器不太靠谱哈~~~
网友评论