如何在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必须将属性添加到方法声明中。

以上是 如何在Swift中使用Timer(以前称为NSTimer)? 的全部内容, 来源链接: utcz.com/qa/428768.html

回到顶部