【问题标题】:Animate UILabel with progress percentage swift使用进度百分比快速为 UILabel 制作动画
【发布时间】:2016-10-24 15:29:37
【问题描述】:

我正在尝试为 UILabel 设置动画,使其从 0% 变为(插入数字)%,并在 1 秒的持续时间内显示中间的每个数字..

直到现在我都失败了,我快要疯了:-)

我什至还没有达到我可以设置持续时间的部分。到目前为止我所做的(但失败了)是这样的:

        var current: Int = Int(0.0 * 100)
        let endValue: Int = Int(toValue * 100)


        if current < endValue {


            self.progressLabel.text = "\(current)%"

            current += Int(0.01 * 100)
        }

toValue 是一个 Double,它在函数被调用时接收。 任何帮助都会很棒!

编辑: 我使用此代码使其在 uilabel 中显示正确的endValue,并在 viewDidLoad 之前将var current... 向上移动。现在的问题是它没有显示 progressLabel.text.. 中的 current 和 endValue 之间的数字。

while current <= endValue {
            self.progressLabel.text = "\(current)%"
            current = current + Int(0.01 * 100)
        }

【问题讨论】:

  • 您是否放置了一个调试点来检查您的current 是否更新为正确的值?
  • 您确定正在调用该函数吗?哪个部分不完全工作?
  • @ZacKwan 我在当前应该更新之后添加了 print(current) 。我唯一得到的是一个 1.. 那甚至不是 endValue?
  • 这解释了为什么它没有更新,因为它只调用一次。你能展示一下这个函数是如何被调用的吗?
  • 很难说没有看到更多,但看起来你每次调用它时都会重置当前。

标签: ios swift animation uilabel


【解决方案1】:

这是一个不依赖计时器的函数,而是使用 GCD 中的 DispatchQueue asyncAfter 方法。

func updateCounter(currentValue: Int, toValue: Double) {
        if currentValue <= Int(toValue * 100) {
            progressLabel.text = "\(currentValue)%"
            let dispatchTime: DispatchTime = DispatchTime.now() + Double(Int64(1.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
            DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: {
                self.updateCounter(currentValue: currentValue + 1, toValue: toValue)
            })
        }
    }

用 this 调用它会产生 0-10 的计数:

updateCounter(currentValue: 0, toValue: 0.1)

【讨论】:

    【解决方案2】:

    您最近更新的代码中现在遇到的问题是您的程序不会在每次更改电流时更新 UILabel。 while 循环将继续,直到当前达到最终值,然后您的 UILabel 将被更新一次。

    如本答案所述,使用计时器可能会对您有所帮助:

    How to make a countdown with NSTimer on Swift

    创建一个将 UILabel 的当前值加一的方法,然后使用计时器每秒调用一次该方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      相关资源
      最近更新 更多