问题
I'm using the NSTimer, with this code:
- (IBAction)start:(id)sender {
MainInt = 0;
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countup) userInfo:nil repeats:YES];
}
How can I display milliseconds and minutes also?
Didn't find any simple yet working method.
回答1:
For milliseconds use:
timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(countup)userInfo:nil repeats:YES];
For minutes use:
timer = [NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(countup)userInfo:nil repeats:YES];
回答2:
Make a shorter interval, like 0.1f
timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(countup)userInfo:nil repeats:YES];
and use NSDateFormatter
to display the counter. An example for the NSDateFormatter
can be found here: timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countup)userInfo:nil repeats:YES];
How the NSDateFormatter works is explained very well here: How to handle different date time formats using NSDateFormatter
Your timer should update a float variable where it stores the milliseconds.
Sample:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"mm:ss:SSS"];
NSTimeInterval interval = [startDate timeIntervalSinceNow]*-1;
NSString *clock = [formatter stringFromDate:[NSDate dateWithTimeInterval:interval sinceDate:startDate]];
But you should go Roy Sharon answer.
来源:https://stackoverflow.com/questions/12026939/seconds-to-minutes-hours-milliseconds