3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift カウントアップアニメーション

Posted at

概要

よくある、数字がカウントアップしていくアニメーション

前提条件

  • 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
	}

参考

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?