如何制作以hh:mm:ss:ms计算的Swift 3.0计时器

时间:2016-11-11 14:48:51

标签: ios swift timer swift3 selector

我在Swift timer in milliseconds中关注了DuncanC的解决方案。代码如下:

startTime = NSDate.timeIntervalSinceReferenceDate
Timer.scheduledTimer(timeInterval: 0.02,
                                           target: self,
                                           selector: Selector(("advanceTimer:")),
                                           userInfo: nil,
                                           repeats: true)


func advanceTimer(timer: Timer)
{
    //Total time since timer started, in seconds
    self.time = NSDate.timeIntervalSinceReferenceDate - startTime
    //The rest of your code goes here
}

Xcode建议我将Swift 3.0的NSDate.timeIntervalSinceReferenceDate()更改为NSDate.timeIntervalSinceReferenceDate,将startTime: NSTimeInterval更改为startTime: TimeInterval。 我的代码产生错误:

  

由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [MyGame.GameScene advanceTimer:]:无法识别的选择器发送到实例

2 个答案:

答案 0 :(得分:3)

在Swift 3中Selector语法已更改,现在您需要通过操作传递第一个参数标签,selector应该像#selector(self.advanceTimer(timer:))

Timer.scheduledTimer(timeInterval: 0.02,
                     target: self,
                     selector: #selector(self.advanceTimer(timer:)),
                     userInfo: nil,
                     repeats: true)

答案 1 :(得分:1)

advanceTimer(timer:)应根据Swift API Design Guidelines以不同方式声明,您应该使用Swift的原生Date代替NSDate,并且选择器语法已更改,因此您的代码将会现在写成这样:

startTime = NSDate.timeIntervalSinceReferenceDate
Timer.scheduledTimer(timeInterval: 0.02,
                     target: self,
                     selector: #selector(advanceTimer),
                     userInfo: nil,
                     repeats: true)

func advanceTimer(_ timer: Timer)
{
    //Total time since timer started, in seconds
    self.time = NSDate.timeIntervalSinceReferenceDate - startTime
    //The rest of your code goes here
}

此外,Timer有基于闭包的新方法,因此现在可以将整个事情简化为:

startTime = NSDate.timeIntervalSinceReferenceDate
Timer.scheduledTimer(withTimeInterval: 0.02, repeats: true) { timer in
    //Total time since timer started, in seconds
    self.time = NSDate.timeIntervalSinceReferenceDate - startTime
    //The rest of your code goes here
}