开发者

How can I create a count up timer with the format seconds:milliseconds?

I'm diving into iOS development and I'm trying to create a count up timer in one of my views. I have the NSTimer code figured out to call a selector once every 0.04 seconds that updates the UILabel. Where I'm having trouble is with the formatting of the current time (starting initially at 00:00). I figured the best way to do this was using the NSDate class, and related classes (NSDateFormatter, NSDateComponents, etc.), but the manipulating of the dates and formats is really confusing me and the code is getting unwieldy quickly. I was hoping there are some SO users that are comfortable using the NSDate class that could help me figure out a simple way to calculate the current time for a count up timer and convert it to an NString with the format 'seconds:mi开发者_运维技巧lliseconds'.

I'd be happy to post my initial attempt at the NSDate code if requested, but I won't initially because it's really of no use and embarrassing :)


If you just want to display time elapsed since you started your timer you can store starting date somewhere (say, startDate variable) and calculate time interval using current date. Something like the following should work:

NSTimeInterval passed = [[NSDate date] timeIntervalSinceDate: startDate]; 
double intPart;
double fract = modf(passed, &intPart);
label.text = [NSString stringWithFormat:@"%d:%.2f", (int)intPart, fract];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜