在Swift中,计时器用于创建重复任务以延迟安排工作。这是一个以前称为NSTimer的类。 Swift的计时器类提供了一种灵活的方式来安排将来一次或重复进行的工作。
创建重复计时器
我们可以使用以下语法创建并启动重复计数器:
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
让我们看一个示例来演示如何创建重复计数器:
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fire), userInfo: nil, repeats: true) @objc func fire() { print("FIRE!!!") }
在上面的例子中,
- 使用Timer.scheduledTimer(...)类方法创建一个计时器。该方法的返回值分配给常数计时器。现在此常量包含对计时器的引用,将在以后使用。
- ScheduledTimer()的参数是1秒的计时器间隔。它使用一种称为target-action的机制,将某些userInfo设置为nil,并将参数repeats设置为true。
- 我们还编写了一个函数fire()。这是计时器触发时(即大约每秒)触发的函数。通过将target设置为self并将选择器设置为#selector(fire)表示,只要计时器触发,就需要调用self的函数fire()。
参数
在此示例中,使用5个参数来创建计时器。
- timeInterval - 它指定计时器触发之间的时间间隔(以秒为单位),类型为Double。
- target - 它指定应在其上调用选择器函数的类实例
- selector - 它指定在计时器火灾时调用的函数,其中#selector(...)
- userInfo - 它指定一个字典,其中包含提供给选择器的数据,或者为nil。
- repeats - 它指定此计时器是重复的还是不重复的。
创建非重复计时器
要创建一个非重复计时器,您只需将repeats参数设置为false。计时器只会触发一次,并在之后立即自动失效。
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fire), userInfo: nil, repeats: false) @objc func fire() { print("FIRE!!!") }
使用闭包创建计时器
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { timer in print("FIRE!!!") })
在上面的代码中,最后一个参数块带有一个闭包。闭包本身具有一个参数计时器。
在这里,使用@objc属性是因为它使fire()函数在Objective-C中可用。 Timer类是Objective-C运行时的一部分,这就是我们使用该@objc属性的原因。