I\'m making an app in swift 2 where there is two timers. After 10 seconds I would like another timer to go faster. I have tried doing it like this but it didn\'t work (I\'m tryi
A few of things.
First, you can't change the time interval of a repeating NSTimer
- you need to invalidate the first timer and schedule a new one for the new interval.
Second a >= comparison on a string won't work for what you are trying to achieve.
Finally, you have fallen into the same bad habit as many Swift programmers and initialised your timer variables needlessly only to subsequently throw those timers away. You should use either an optional or an implicitly unwrapped optional
@IBOutlet var displayTimeLabel: UILabel!
var startTime:NSDate?
var timer : NSTimer?
var timer2: NSTimer?
var time = 2.0
@IBAction func Start(sender: UIButton) {
if (self.timer2 == nil) {
self.time=2.0
self.timer2 = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "updateTime", userInfo: nil, repeats: true)
self.startTime = NSDate()
self.timer = NSTimer.scheduledTimerWithTimeInterval(time, target: self, selector: "timer:", userInfo: nil, repeats: true)
}
}
func timer(timer: NSTimer){
//code
}
func updateTime() {
let currentTime = NSDate.timeIntervalSinceNow()
var elapsedTime = -self.startTime!.timeIntervalSinceNow()
if (elapsedTime >10.0 && self.time==2.0) {
timer.invalidate()
self.time=1.0
self.timer = NSTimer.scheduledTimerWithTimeInterval(time, target: self, selector: "timer:", userInfo: nil, repeats: true)
}
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (NSTimeInterval(minutes) * 60)
let seconds = UInt8(elapsedTime)
elapsedTime -= NSTimeInterval(seconds)
let fraction = UInt8(elapsedTime * 100)
displayTimeLabel.text = String(format: "%02d:%02d.%02d", minutes,seconds,fraction)
}