如何在Swift中使用NSTimer?

编程入门 行业动态 更新时间:2024-10-26 14:41:21
本文介绍了如何在Swift中使用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中使用NSTimer?

本文发布于:2023-11-26 21:58:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635361.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Swift   NSTimer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!