Reputation: 113
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(setNeedsDisplay) userInfo:self repeats:YES];
I want know how to write the code above in swift.thank u.
Upvotes: -1
Views: 292
Reputation: 181
var timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.setNeedsDisplay), userInfo: self, repeats: true)
Upvotes: 0
Reputation: 3960
The code can be written as
Swift 2
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("setNeedsDisplay"), userInfo: self, repeats: true)
func setNeedsDisplay() {
}
Swift 3, 4, 5
var timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.setNeedsDisplay), userInfo: self, repeats: true)
@objc func setNeedsDisplay() {
}
Upvotes: 0
Reputation: 2423
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()
}
}
Upvotes: 0
Reputation: 5967
Sample usage NSTimer's
timer schedule event -
// 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!) {
...
}
Note : This was just the sample usage, you can change the variable and method names as per your context.
Upvotes: 0