gpt4 book ai didi

ios - 如何在 Swift 中使用 Timer(以前称为 NSTimer)?

转载 作者:IT王子 更新时间:2023-10-29 04:54:51 27 4
gpt4 key购买 nike

我试过了

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属性。

关于ios - 如何在 Swift 中使用 Timer(以前称为 NSTimer)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24007518/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com