Ios 使用Swift中的NSTimer,使用多个十进制插槽倒计时

Ios 使用Swift中的NSTimer,使用多个十进制插槽倒计时,ios,xcode,swift,nstimer,countdowntimer,Ios,Xcode,Swift,Nstimer,Countdowntimer,例如,我想制作一个计时器从10.0000000开始的应用程序,我希望它能完美地倒计时 以下是我目前的代码: import UIKit class ViewController: UIViewController { @IBOutlet weak var labelTime: UILabel! var counter = 10.0000000 var labelValue: Double { get { return NSNu

例如,我想制作一个计时器从10.0000000开始的应用程序,我希望它能完美地倒计时 以下是我目前的代码:

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秒。有什么想法吗?我应该对代码做哪些更改?
谢谢

计时器不是超精确的,NSTimer的分辨率约为1/50秒

另外,iPhone屏幕的刷新率是60帧/秒,因此运行计时器的速度超过60帧/秒是毫无意义的

与其尝试使用计时器在每次触发时减少某些内容,不如创建一个每秒触发50次的计时器,并让它使用时钟数学根据剩余时间更新显示:

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

您是否试图使其在一秒钟内显示0.0000001和.9999999之间的每个组合?为了显示每个数字,屏幕实际上必须更新一亿次。在任何现有技术或未来技术上,都不可能在一秒钟内做到这一点。屏幕本身的更新速度不能超过每秒60次,因此这是最快的,这将为您工作

您可以尝试对该速率使用NSTimer(1/60=0.0167)。NSTimer本身不能保证非常精确。为了在每一帧更新屏幕,您必须使用
CADisplayLink
()


这使您有机会在每次帧更新时运行选择器,这与系统根据定义更改帧的速度一样快。

我稍微编辑了我的示例代码。查看更新版本。这非常有效!非常感谢。在swift中,如何使我的浮点只有7个小数点?似乎它对@“%.07f”不起作用,它给了你什么?“它不起作用”是难以置信的,令人发狂的没有帮助。啊哈,对不起。它正在工作,必须删除“@”哦,对不起。这是一个很难打破的客观习惯。(已修复)请编辑代码并将其拆分为几行。当它在一条线上时,Hart需要阅读(和理解)。或者这是斯威夫特的常见做法?