【问题标题】:Counting up/down numbers animation向上/向下计数动画
【发布时间】:2016-08-08 09:24:18
【问题描述】:

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

我希望当我从一个视图滑动到另一个视图时,数字将从 0 开始并向上计数,直到它达到正确的数字(或者如果数字是负数 - 向下计数),就像这个 gif 所示:

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

我该怎么做?

谢谢!

【问题讨论】:

  • @khuong291 我尝试了 while 语句每次都添加到标签 1 但它不起作用
  • @matiboo 谢谢!这就是我正在搜索的内容

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


【解决方案1】:

您可以使用 NSTimer 来实现这一点。

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

像这样创建布局:

然后在你的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()
        }
    }
}

它会起作用的。

【讨论】:

  • 你需要在完成后使 NSTimer 失效
  • 为什么?如果我不使其无效,在这种情况下会发生什么?
  • 它将继续被运行循环调用,这是没有意义的和浪费的。此外,如果您多次调用startButtonTapped,则会将多个计时器添加到运行循环中,这也是一种浪费,并可能导致不希望的结果。
  • 好的。更新。谢谢@originaluser2。
  • 谢谢!它会起作用,我为此使用UICountingLabel,但您的回答也会起作用,再次感谢!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多