我试过了
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'
Answer 1:
这将工作:
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
}
对于斯威夫特4,其中你想选择的方法必须暴露的Objective-C,从而@objc
属性必须被添加到方法声明。
Answer 2:
重复事件
您可以使用一个定时器来多次做一个动作,如下面的例子中看出。 计时器调用更新标签每半秒的方法。
下面是该代码:
import UIKit
class ViewController: UIViewController {
var counter = 0
var timer = Timer()
@IBOutlet weak var label: UILabel!
// start timer
@IBAction func startTimerButtonTapped(sender: UIButton) {
timer.invalidate() // just in case this button is tapped multiple times
// start the timer
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
}
// stop timer
@IBAction func cancelTimerButtonTapped(sender: UIButton) {
timer.invalidate()
}
// called every time interval from the timer
func timerAction() {
counter += 1
label.text = "\(counter)"
}
}
延迟事件
你也可以使用一个计时器来安排一次性事件在未来的一段时间。 从上面的例子中的主要区别是,你使用repeats: false
的,而不是true
。
timer = Timer.scheduledTimer(timeInterval: 2.0, target: self, selector: #selector(delayedAction), userInfo: nil, repeats: false)
上面的例子中调用名为方法delayedAction
定时器被设置在两秒钟后。 这是不能重复的,但你仍然可以调用timer.invalidate()
如果您需要取消事件它发生之前。
笔记
- 如果启动您的计时器实例多次的任何机会,请确保您先废止旧计时器实例。 否则你就失去了参考定时器,你不能阻止它了。 (参见此Q&A )
- 在不需要时不使用定时器。 见的定时器部分能源效率指南iOS应用 。
有关
Answer 3:
更新斯威夫特4,充分利用用户信息:
class TimerSample {
var timer: Timer?
func startTimer() {
timer = Timer.scheduledTimer(timeInterval: 5.0,
target: self,
selector: #selector(eventWith(timer:)),
userInfo: [ "foo" : "bar" ],
repeats: true)
}
// Timer expects @objc selector
@objc func eventWith(timer: Timer!) {
let info = timer.userInfo as Any
print(info)
}
}
Answer 4:
作为iOS的10也有一个新的基于块定时器工厂方法,该方法比使用清洁器选择:
_ = Timer.scheduledTimer(withTimeInterval: 5, repeats: false) { timer in
label.isHidden = true
}
Answer 5:
迅速3,预iOS的10
func schedule() {
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(timeInterval: 20, target: self,
selector: #selector(self.timerDidFire(timer:)), userInfo: nil, repeats: false)
}
}
@objc private func timerDidFire(timer: Timer) {
print(timer)
}
斯威夫特3,iOS的10+
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: false) { timer in
print(timer)
}
}
笔记
- 它需要在主队列
- 回调函数可以是公共的,私人的,...
- 回调函数必须
@objc
Answer 6:
请与:
var timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("update"), userInfo: nil, repeats: true);
Answer 7:
您将需要使用定时器来代替的NSTimer斯威夫特3。
下面是一个例子:
Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: #selector(YourController.update),
userInfo: nil,
repeats: true)
// @objc selector expected for Timer
@objc func update() {
// do what should happen when timer triggers an event
}
Answer 8:
为迅速3的Xcode 8.2(最好有块,但是如果你编译iOS9,想用户信息):
...
self.timer = Timer(fireAt: fire,
interval: deltaT,
target: self,
selector: #selector(timerCallBack(timer:)),
userInfo: ["custom":"data"],
repeats: true)
RunLoop.main.add(self.timer!, forMode: RunLoopMode.commonModes)
self.timer!.fire()
}
func timerCallBack(timer: Timer!){
let info = timer.userInfo
print(info)
}
Answer 9:
SimpleTimer(SWIFT 3.1)
为什么?
这是一个快捷简单的定时器类,使您可以:
用法:
SimpleTimer(interval: 3,repeats: true){print("tick")}.start()//Ticks every 3 secs
码:
class SimpleTimer {/*<--was named Timer, but since swift 3, NSTimer is now Timer*/
typealias Tick = ()->Void
var timer:Timer?
var interval:TimeInterval /*in seconds*/
var repeats:Bool
var tick:Tick
init( interval:TimeInterval, repeats:Bool = false, onTick:@escaping Tick){
self.interval = interval
self.repeats = repeats
self.tick = onTick
}
func start(){
timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(update), userInfo: nil, repeats: true)//swift 3 upgrade
}
func stop(){
if(timer != nil){timer!.invalidate()}
}
/**
* This method must be in the public or scope
*/
@objc func update() {
tick()
}
}
Answer 10:
在斯威夫特3像这样与@objc:
func startTimerForResendingCode() {
let timerIntervalForResendingCode = TimeInterval(60)
Timer.scheduledTimer(timeInterval: timerIntervalForResendingCode,
target: self,
selector: #selector(timerEndedUp),
userInfo: nil,
repeats: false)
}
@objc func timerEndedUp() {
output?.timerHasFinishedAndCodeMayBeResended()
}
Answer 11:
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(createEnemy), userInfo: nil, repeats: true)
创造有趣的名称为createEnemy
fund createEnemy ()
{
do anything ////
}
Answer 12:
如果你初始化定时器的方法
let timer = Timer(timeInterval: 3, target: self, selector: #selector(update(_:)), userInfo: [key : value], repeats: false)
func update(_ timer : Timer) {
}
然后使用方法等选择将其添加到循环就不会被调用
RunLoop.main.add(timer!, forMode: .defaultRunLoopMode)
注意:如果你想要这个重复做重复的真实和保持定时器的参考否则Update方法不会被调用。
如果您在使用此方法。
Timer.scheduledTimer(timeInterval: seconds, target: self, selector: #selector(update(_:)), userInfo: nil, repeats: true)
保留供以后使用的参考,如果重复是真实的。
Answer 13:
的NSTimer已更名为定时器的雨燕4.2。 此语法将在4.2的工作:
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)
文章来源: How can I use NSTimer in Swift?