之前只是用過以下兩種方式使用計時器。
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()
}
}
參考鏈接:
http://www.lxweimin.com/p/67bab7e8f6b2
這個是一朋友給我寫的上篇實現的縮放動畫實現的閃跳功能,記錄一下這個定時器的使用吧。還是動畫實現好,定時器不太靠譜哈~~~