计数上/下数字动画

时间:2016-04-16 11:25:19

标签: ios objective-c iphone swift cocoa-touch

我有一个UIPageViewController,其中每个VC的中心都有一个数字。

我希望当我从视图滑动到视图时,数字将从0开始并计数直到达到正确的数字(或者如果数字为负数 - 倒数),就像在这个gif中一样:

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

我该怎么做?

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以使用NSTimer来实现此目的。

以下是我为您创建的示例项目。

像这样创建布局:

enter image description here

然后在你的ViewController中这样做:

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()
        }
    }
}

它会起作用。

答案 1 :(得分:1)

不要使计时器和失效等过于复杂

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)))"
            }
        }
    }
}