Counting up/down numbers animation

前端 未结 2 1778
野趣味
野趣味 2021-01-23 18:42

I have an UIPageViewController with a number in the center of each VC in it.

I want that when I swipe from view to view, the number will begin

相关标签:
2条回答
  • 2021-01-23 19:34

    You can use NSTimer to achieve this.

    Here is example project I created for you.

    Create layout like this:

    Then in your ViewController do like so:

    import UIKit
    
    class ViewController: UIViewController {
    
        @IBOutlet var countingLabel: UILabel!
        var number = 0
        var destinationNumber = 30
        var timer: NSTimer!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    
        @IBAction func startButtonTapped(sender: AnyObject) {
            timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "countUp", userInfo: nil, repeats: true)
        }
    
        func countUp() {
            if number < destinationNumber {
                number += 1
                countingLabel.text = "\(number)"
            } else {
                timer.invalidate()
            }
        }
    }
    

    It will work.

    0 讨论(0)
  • 2021-01-23 19:47

    Do not overcomplicate with timers and invalidations, etc.

    extension UILabel {    
        func countAnimation(upto: Double) {
            let from: Double = text?.replace(string: ",", replacement: ".").components(separatedBy: CharacterSet.init(charactersIn: "-0123456789.").inverted).first.flatMap { Double($0) } ?? 0.0
            let steps: Int = 20
            let duration = 0.350
            let delay = duration / Double(steps)
            let diff = upto - from
            for i in 0...steps {
                DispatchQueue.main.asyncAfter(deadline: .now() + delay * Double(i)) {
                    self.text = "\(from + diff * (Double(i) / Double(delay)))"
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题