swift - 使用 NSDate 和 NSTimer 进行游戏计时器? swift

标签 swift timer nsdate nstimer nstimeinterval

我想在特定日期和时间启动计时器,然后使用该开始时间作为游戏其余部分的游戏计时器。使用“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 时,它被推断为 Int 类型

var counter = 0

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

var counter: NSTimeInternval = 0.0

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

gameTimerLabel.text = "\(counter)"

这是一个使用 NSTimer 作为计数器的示例 View Controller ,它以秒为单位:

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

关于swift - 使用 NSDate 和 NSTimer 进行游戏计时器? swift ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36362809/

相关文章:

iphone - 如何格式化字符串中的日期?

swift - 错误 : unable to spawn process (Argument list too long) in Xcode Build

ios - 如何使用 RxSwift 和 RxSwiftDataSources 将 TableView 与代表不同数据类型的多个部分绑定(bind)?

objective-c - iOS - 如何比较两个 ISO 8601 格式的时间?

java-me - 如何在 J2ME 或 LWUIT 中创建计时器?

node.js - 当 Mongoose 计时器到期时执行脚本

ios - 当我们过年时显示每个月的星期和日期列表

ios - 如何在不影响行间距的情况下截断 UILabel?

ios - UIImageView 是否有任何 UV 坐标(或类似坐标)?

c++ - 如何安全地删除 C++ 中的 posix 计时器?