使用Swift中的NSTimer在几个十进制插槽中倒计时 [英] Countdown with several decimal slots, using NSTimer in Swift

查看:216
本文介绍了使用Swift中的NSTimer在几个十进制插槽中倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个以10.0000000为例的计时器应用程序,我希望它完美倒计时
这是我的代码到目前为止:

I want to make an app that has a timer starting at 10.0000000 for example, and I want it to countdown perfectly Here's my code so far:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var labelTime: UILabel!

    var counter = 10.0000000

    var labelValue: Double {
        get {
            return NSNumberFormatter().numberFromString(labelTime.text!)!.doubleValue
        }
        set {
            labelTime.text = "\(newValue)"
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        labelValue = counter
        var timer = NSTimer.scheduledTimerWithTimeInterval(0.0000001, target: self, selector: ("update"), userInfo: nil, repeats: true)
    }

    func update(){
        labelValue -= 0.0000001
    }


}

我的倒计时真的很慢,它只是不起作用,需要1小时才能达到0秒,而不是仅仅10秒。有任何想法吗?我应该对代码做出哪些更改?
谢谢

What happens is that my countdown is really slow, it's just not working and it would take like 1 hour to get to 0 seconds, instead of just 10 seconds. Any ideas? What changes should I make to my code? Thanks

推荐答案

定时器不是超精准的,NSTimer的分辨率大约是1/50秒。

Timers are not super-accurate, and the resolution of NSTimer is about 1/50th of a second.

另外,iPhone屏幕的刷新率是60帧/秒,因此以比这更快的速度运行计时器完全没有意义。

Plus, the refresh rate of the iPhone screen is 60 frames/second, so it's totally pointless to run your timer any faster than that.

不是每次触发时都尝试使用定时器递减某些内容,而是创建一个每秒触发50次的定时器,并让它使用时钟数学来根据剩余时间更新显示:

Rather than trying to use a timer to decrement something every time it fires, create a timer that fires like 50 times a second, and have it use clock math to update the display based on the remaining time:

var futureTime: NSTimeInterval 

override func viewDidLoad() {
    super.viewDidLoad()
    labelValue = counter

    //FutureTime is a value 10 seconds in the future.
    futureTime = NSDate.timeIntervalSinceReferenceDate() + 10.0 

    var timer = NSTimer.scheduledTimerWithTimeInterval(
      0.02, 
      target: self, 
      selector: ("update:"), 
      userInfo: nil, 
      repeats: true)
}

func update(timer: NSTimer)
{
  let timeRemaining = futureTime - NSDate.timeIntervalSinceReferenceDate()
  if timeRemaining > 0.0
  {
    label.text = String(format: "%.07f", timeRemaining)
  }
  else
  {
    timer.invalidate()
    //Force the label to 0.0000000 at the end
    label.text = String(format: "%.07f", 0.0)
  }
}

这篇关于使用Swift中的NSTimer在几个十进制插槽中倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆