NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(setNeedsDisplay) userInfo:self repeats:YES];
我想知道如何在 swift.thank 中编写上面的代码。
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(setNeedsDisplay) userInfo:self repeats:YES];
我想知道如何在 swift.thank 中编写上面的代码。
示例使用NSTimer's
计时器计划事件 -
// create a timer instance
let timer = NSTimer(timeInterval: 1.0, target: self, selector: "timerEventTriggered:", userInfo: nil, repeats: true)
// adding timer to current run loop
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
// implement the event which is triggered by scheduled timer
func timerEventTriggered(timer:NSTimer!) {
...
}
注意:这只是示例用法,您可以根据上下文更改变量和方法名称。
var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("yourFunction"), userInfo: nil, repeats: true)
func yourFunction() {
// Do something
}
/////other way.......
dispatch_after(timer, dispatch_get_main_queue()) { () -> Void in
//do same like in yourFunction()
}
}
代码可以写成
斯威夫特 2
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("setNeedsDisplay"), userInfo: self, repeats: true)
func setNeedsDisplay() {
}
斯威夫特 3, 4, 5
var timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.setNeedsDisplay), userInfo: self, repeats: true)
@objc func setNeedsDisplay() {
}
var timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.setNeedsDisplay), userInfo: self, repeats: true)