Reputation: 13
Would like to ask, how to properly format an NSTimer
in the interval of 0.01
?
I would like to have something like 00:00.00
(mins, sec, msec)
When I run my code:
...
@IBAction func btn_play(sender: AnyObject) {
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
}
...
func result() {
count++
lbl_time.text = String(count)
}
...
I receive something like 1123
( stands for 11 seconds 23 msecs)
How would you transform it to eg:
00:11.23
I've tried some stuff with "substring" but with no sucess. I'm new to Swift, so I'm not aware what possibilities I have here. thx!
Upvotes: 0
Views: 609
Reputation: 154573
Use integer division /
and modulo %
to calculate the values for minutes, seconds, and hundredths of a second, and then use the String
convenience initializer which takes a format
string to add the leading zeros and colons:
let count = 1234
let str = String(format:"%02d:%02d:%02d", (count/6000)%100, (count/100)%60, count%100)
This functionality comes from the Foundation
framework. To use this convenience initializer for String
, you must import Foundation
(note: Foundation
is imported by both import UIKit
(iOS) and import Cocoa
(OS X), so you usually don't import Foundation
explicitly).
The NSString
formatting methods follow the IEEE printf specification.
Upvotes: 1