I have a working countdown which you can increase by pushing the add button and thats what the time counts down from (so basically a user can set the countdown)
I would like to display the starting time as 00:00 as it does in my label.
When I click button to increase the countdown it just begins at 1 obviously because at the moment its just an Int
can I create an array and increase the individual indexes, then display them within my label?
can anyone help with this or point me in the write code direction from what I have below thanks
var timeArray: [Double : Double] = [00, 00]
var timer = NSTimer()
var countdown = 0
func runTimer() {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self,
selector:Selector("updateTimer"), userInfo: nil, repeats: true)
}
func updateTimer() {
if countdown > 0 {
countdown--
TimerLabel.text = String(countdown)
} else {
countdown = 0
TimerLabel.text = String(countdown)
}
}
@IBOutlet weak var TimerLabel: UILabel!
@IBAction func IncreaseCountdown(sender: AnyObject) {
countdown++
TimerLabel.text = String(countdown)
}
@IBAction func StartCountdown(sender: AnyObject) {
runTimer()
}
@IBAction func StopCountdown(sender: AnyObject) {
timer.invalidate()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Your syntax for timeArray
is creating a Dictionary
and not an Array
. I also suggest you use Int
instead of Double
:
var timeArray:[Int] = [0, 0]
To create the label for your text field:
// This format will create a string with 2 digits for minute and second with
// a leading 0 for each if needed like "00:00"
TimerLabel.text = String(format: "%02d:%02d", timeArray[0], timeArray[1])
When you create your timer, convert your time array back into a simple countdown:
let countdown = timeArray[0] * 60 + timeArray[1]
An entirely different approach which would work would to be just to store your time as integer seconds internally and just to display it as minutes and seconds.
let countdown = 100 // 1 minute, 40 seconds
TimerLabel.text = String(format: "%02d:%02d", countdown/60, countdown%60)