Reputation: 13
Hello I am developing a countdown timer,which has to stop after 8 hours. Here it is:
import UIKit
class ViewController: UIViewController {
var timer = NSTimer()
var counter = 0
@IBOutlet weak var Label: UILabel!
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.
}
@IBAction func Start(sender: AnyObject) {
counter = 28800
Label.text = String(counter)
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("updateTimer"), userInfo: nil, repeats: true)
}
func updateTimer () {
counter -= 1
Label.text = String(counter)
}
@IBAction func Stop(sender: AnyObject) {
timer.invalidate()
}
}
But in stead of having 28800 seconds (which is 8hours)I want to display 08:00:00 , 07:59:59 , 07:59:58, so on... At the moment it is showing 28800, 28799, 28798, so on. Do you have an idea how to format it as a real clock (08:00:00)?
Upvotes: 1
Views: 1506
Reputation: 33
I had the same problem and pretty much a noob in xcode/swift - but after reviewing several sources, here's what I put together that works for me:
Replace your:
func updateTimer () {
counter -= 1
Label.text = String(counter)
}
With this:
func updateTimer () {
counter -= 1
let hours = Int(counter) / 3600
let minutes = Int(counter) / 60 % 60
let seconds = Int(counter) % 60
Label.text = String(format: "%02i:%02i:%02i",hours,minutes,seconds)
}
(xcode 8.1 warns about use of "let" or "var" for hours/minutes/seconds, but it still works)
Result look like:
00:00:00
Upvotes: 2