本文介绍了如何在 Swift 中使用 Timer(以前称为 NSTimer)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过了
var timer = NSTimer()
timer(timeInterval: 0.01, target: self, selector: update, userInfo: nil, repeats: false)
但是,我有一个错误说
'(timeInterval: $T1, target: ViewController, selector: () -> (), userInfo: NilType, repeats: Bool) -> $T6' is not identical to 'NSTimer'
推荐答案
这会起作用:
override func viewDidLoad() {
super.viewDidLoad()
// Swift block syntax (iOS 10+)
let timer = Timer(timeInterval: 0.4, repeats: true) { _ in print("Done!") }
// Swift >=3 selector syntax
let timer = Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
// Swift 2.2 selector syntax
let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: #selector(MyClass.update), userInfo: nil, repeats: true)
// Swift <2.2 selector syntax
let timer = NSTimer.scheduledTimerWithTimeInterval(0.4, target: self, selector: "update", userInfo: nil, repeats: true)
}
// must be internal or public.
@objc func update() {
// Something cool
}
对于 Swift 4,要获取选择器的方法必须暴露给 Objective-C,因此必须在方法声明中添加 @objc
属性.
For Swift 4, the method of which you want to get the selector must be exposed to Objective-C, thus @objc
attribute must be added to the method declaration.
这篇关于如何在 Swift 中使用 Timer(以前称为 NSTimer)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!