概要
よくある、数字がカウントアップしていくアニメーション
前提条件
- Swift 4.2
- Xcode 10.2
var startTime: CFTimeInterval!
var fromValue: Int!
var toValue: Int!
var duration: TimeInterval!
func animate(from fromValue: Int, to toValue: Int, duration: TimeInterval) {
text = "\(fromValue)"
self.startTime = CACurrentMediaTime()
self.fromValue = fromValue
self.toValue = toValue
self.duration = duration
let link = CADisplayLink(target: self, selector: #selector(update))
link.add(to: .current, forMode: .commonModes)
}
@objc func update(link: CADisplayLink) {
let dt = (link.timestamp - startTime) / executionInterval
if dt >= 1.0 {
self.label.text = toValue
stopDisplayLink()
return
}
let current = Int(Double(toValue - fromValue) * dt) + fromValue
self.label.text = current
}