使用 NSDate 和 NSTimer 的游戏计时器? swift

Game Timer using NSDate with NSTimer? swift

我想在特定的日期和时间启动计时器,然后将该开始时间用作游戏剩余时间的游戏计时器。使用 "timeIntervalSinceDate" 会给我秒数,但随后尝试让秒数显示在 gameTimerLabel 上将不起作用。我可能会以错误的方式来解决这个问题。欢迎任何建议。

override func viewWillAppear(animated: Bool) {
    let dateFormatter = NSDateFormatter()


    dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
    let dateAsString1 = "Fri, 1 April 2016 11:30:00 MST"
    let date1 = dateFormatter.dateFromString(dateAsString1)!
    var currentTime = NSDate()
   var counter = 0
    gameTimerLabel.text = String(counter)
    gameTimerLabel.text = counter  //<- Error:Cannot assign value to type 'Int' to type 'String?'
    counter = date1.timeIntervalSinceDate(currentTime)  //<- Error:Cannot assign value of type 'NSTimeInterval' (aka 'Double') to type 'Int'

}

这里有几件事

首先,当你声明计数器时,它被推断为 Int 类型

var counter = 0

您可以通过添加 .0 或指定其类型将其声明为双精度型:

var counter: NSTimeInternval = 0.0

接下来,你可以使用字符串互操作来显示字符串中的count变量,像这样:

gameTimerLabel.text = "\(counter)"

这是一个使用 NSTimer 作为计数器的示例视图控制器,它以秒为单位计数:

class ViewController: UIViewController {

// Setup a timer and a counter for use
var timer   = NSTimer()
var counter : NSTimeInterval = 0

@IBOutlet weak var label: UILabel!

// Invalidest the timer, resets the counter and udpates the label
@IBAction func resetTimer(sender: AnyObject) {

    // Invalidate the timer, reset the label.
    self.timer.invalidate()
    self.label.text = ""
    self.counter    = 0
}

// A button that when pressed starts and stops the timer
// There's no pause/resume, so it's invalidated & created again
// But the counter value reamins the same
@IBAction func timerBttnTouched(sender: AnyObject) {

    if self.timer.valid {

        self.timer.invalidate()

    } else {

        self.setupTimer()
    }
}

// Does the actual counting everytime the timer calls this method
func timerFired() {

    self.counter += 1
    self.label.text = "\(self.counter)"
}

// Setups a timer, adds it to the run loop and specifies what method should fire when the timer fires
func setupTimer() {

    // Setupt the timer, this will call the timerFired method every second
    self.timer = NSTimer(
        timeInterval: 1,
        target: self,
        selector: #selector(self.timerFired),
        userInfo: nil,
        repeats: true)

    // Add the timer to the run loop
    NSRunLoop.currentRunLoop().addTimer(
        self.timer,
        forMode: NSDefaultRunLoopMode)
}
}

使用计时器时需要注意的重要一点是,当您需要它们时,它们可能并不总是 准确地被调用 ,这应该根据您在使用时所需的精度来考虑一个计时器。

正如评论中所讨论的那样,这是使用计时器触发比较两个日期并使用 NSDateComponentsFormatter 生成字符串以供显示的方法的解决方案。初始日期在 viewDidLoad 中生成,但可以在任何地方创建:

class ViewController: UIViewController {

// Setup a timer and a counter for use
var timer   = NSTimer()
var counter : NSTimeInterval = 0

var startDate: NSDate?

override func viewDidLoad() {

    // Set the initial date
    self.startDate = NSDate()
}

@IBOutlet weak var label: UILabel!

// Invalidest the timer, resets the counter and udpates the label
@IBAction func resetTimer(sender: AnyObject) {

    // Invalidate the timer, reset the label.
    self.timer.invalidate()
    self.label.text = ""
    self.counter    = 0
}

// A button that when pressed starts and stops the timer
// There's no pause/resume, so it's invalidated & created again
// But the counter value reamins the same
@IBAction func timerBttnTouched(sender: AnyObject) {

    if self.timer.valid {

        self.timer.invalidate()

    } else {

        self.setupTimer()
    }
}

// Does the actual counting everytime the timer calls this method
func timerFired() {

    let now = NSDate()
    let difference = now.timeIntervalSinceDate(self.startDate!)

    // Format the difference for display
    // For example, minutes & seconds
    let dateComponentsFormatter = NSDateComponentsFormatter()
    dateComponentsFormatter.stringFromTimeInterval(difference)

    self.label.text = dateComponentsFormatter.stringFromTimeInterval(difference)
}

// Setups a timer, adds it to the run loop and specifies what method should fire when the timer fires
func setupTimer() {

    // Setupt the timer, this will call the timerFired method every second
    self.timer = NSTimer(
        timeInterval: 1,
        target: self,
        selector: #selector(self.timerFired),
        userInfo: nil,
        repeats: true)

    // Add the timer to the run loop
    NSRunLoop.currentRunLoop().addTimer(
        self.timer,
        forMode: NSDefaultRunLoopMode)
}
}