CADisplayLinkをTimerのように使うために拡張してみた
2021/01/12
拡張ファイルを追加する
extension CADisplayLink {
class func scheduledDisplayLink(target: Any, selector sel: Selector, addTo runloop: RunLoop = .current, forMode mode: RunLoop.Mode = .common) -> CADisplayLink {
let link = CADisplayLink(target: target, selector: sel)
link.add(to: runloop, forMode: mode)
return link
}
}
使い方
weak var displayLink: CADisplayLink?
func startDisplayLink() {
displayLink = .scheduledDisplayLink(target: self, selector: #selector(myselector))
}
func stopDisplayLink() {
displayLink?.invalidate()
}
@objc func myselector() {
}
Timerとの比較
weak var timer: Timer?
func startTimer() {
timer = .scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(myselector), userInfo: nil, repeats: true)
}
func stopTimer() {
timer?.invalidate()
}
@objc func myselector() {
}