Counting up/down numbers animation

2020-05-06 08:29发布

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 at 0 and count up until it gets to the correct number (or if the number is negative - count down) like in this gif:

https://d13yacurqjgara.cloudfront.net/users/345970/screenshots/2126044/shot.gif

How can I do that?

Thank you!

1条回答
We Are One
2楼-- · 2020-05-06 08:57

You can use NSTimer to achieve this.

Here is example project I created for you.

Create layout like this:

enter image description here

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.

查看更多
登录 后发表回答