【问题标题】:Game Timer using NSDate with NSTimer? swift使用 NSDate 和 NSTimer 的游戏计时器?迅速
【发布时间】:2016-07-21 15:25:34
【问题描述】:

我想在特定的日期和时间启动计时器,然后将该开始时间用作游戏剩余时间的游戏计时器。使用“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'

}

【问题讨论】:

  • 您需要将时间间隔转换为字符串
  • counter 应该声明为 Double

标签: swift timer nsdate nstimer nstimeinterval


【解决方案1】:

这里有几件事

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

var counter = 0

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

var counter: NSTimeInternval = 0.0

接下来,您可以使用字符串互操作性来显示字符串中的计数变量,如下所示:

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

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

正如 cmets 中所讨论的,这里的解决方案是使用计时器来触发比较两个日期并使用 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)
}
}

【讨论】:

  • 我已经添加了这些更改。它现在显示。我怎么算呢?或更新时间以正确计数?
  • 为此,您应该使用 NSTimer,稍后让我在答案中为您提供替代方案。
  • @Ring-Jarvi 我已经用计时器的替代方法更新了我的答案。
  • 您的精确评论是我试图从 NSDate 构建计时器的原因。此计时器在应用程序启动后立即启动正确吗?我试图将其设置为日期和时间。
  • 不,这从按下按钮开始。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多