定時器頻率選項
重複計時器事件
迅速
class ViewController: UIViewController {
var timer = NSTimer()
override func viewDidLoad() {
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector(self.timerMethod()), userInfo: nil, repeats: true)
}
func timerMethod() {
print("Timer method called")
}
func endTimer() {
timer.invalidate()
}
}
Swift 3
class ViewController: UIViewController {
var timer = Timer()
override func viewDidLoad() {
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.timerMethod()), userInfo: nil, repeats: true)
}
func timerMethod() {
print("Timer method called")
}
func endTimer() {
timer.invalidate()
}
}
如果需要,必須手動無效。
迅速
非重複延遲定時器事件
NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: Selector(self.timerMethod()), userInfo: nil, repeats: false)
Swift 3
Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(self.timerMethod()), userInfo: nil, repeats: false)
定時器將在執行一次,3 秒後觸發一次。一旦被解僱,將自動失效。