I have coded my timer with the idea in mind that when my timer reaches 10, it stops. But for some reason, it doesn't.
import Foundation
import UIKit
class SinglePlayer: UIViewController {
var timerCount = 0.0
@IBOutlet weak var timer: UILabel!
var timerVar = NSTimer()
func isCounting() {
timerCount += 0.1
timer.text = "\(timerCount)"
}
override func viewDidLoad() {
super.viewDidLoad()
if timerCount <= 10.0{
timerVar = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "isCounting", userInfo: nil, repeats:true)
} else {
timerVar.invalidate()
}
}
}
You need to put condition in the callback function and not on viewDidLoad
which is only called once on the load.
func isCounting() {
timerCount += 0.1
timer.text = "\(timerCount)"
if timerCount >= 10.0 {
timerVar.invalidate()
}
}