Iphone 使用NSTimer和NSDateFormatter显示时间代码
我很快就要完成我的第一个iphone应用程序了,这是一种快乐。我试图通过在UILabel上显示当前时间(NSDate)的NSTimer,使用当前时间添加运行时间代码。NSDate对我来说运行良好,显示小时、分钟、秒、毫秒。但是我需要每秒显示24帧,而不是毫秒 问题是,我需要每秒的帧与小时、分钟和秒100%同步,所以我不能在单独的计时器中添加帧。我试过了,但帧计时器与日期计时器不同步 有人能帮我解决这个问题吗?有没有办法自定义NSDateFormatter,这样我就可以将日期计时器格式化为每秒24帧?现在我只限于格式化小时、分钟、秒和毫秒 这是我现在使用的代码Iphone 使用NSTimer和NSDateFormatter显示时间代码,iphone,xcode,nstimer,nsdateformatter,Iphone,Xcode,Nstimer,Nsdateformatter,我很快就要完成我的第一个iphone应用程序了,这是一种快乐。我试图通过在UILabel上显示当前时间(NSDate)的NSTimer,使用当前时间添加运行时间代码。NSDate对我来说运行良好,显示小时、分钟、秒、毫秒。但是我需要每秒显示24帧,而不是毫秒 问题是,我需要每秒的帧与小时、分钟和秒100%同步,所以我不能在单独的计时器中添加帧。我试过了,但帧计时器与日期计时器不同步 有人能帮我解决这个问题吗?有没有办法自定义NSDateFormatter,这样我就可以将日期计时器格式化为每秒24
-(void)runTimer {
// This starts the timer which fires the displayCount method every 0.01 seconds
runTimer = [NSTimer scheduledTimerWithTimeInterval: .01
target: self
selector: @selector(displayCount)
userInfo: nil
repeats: YES];
}
//This formats the timer using the current date and sets text on UILabels
- (void)displayCount; {
NSDateFormatter *formatter =
[[[NSDateFormatter alloc] init] autorelease];
NSDate *date = [NSDate date];
// This will produce a time that looks like "12:15:07:75" using 4 separate labels
// I could also have this on just one label but for now they are separated
// This sets the Hour Label and formats it in hours
[formatter setDateFormat:@"HH"];
[timecodeHourLabel setText:[formatter stringFromDate:date]];
// This sets the Minute Label and formats it in minutes
[formatter setDateFormat:@"mm"];
[timecodeMinuteLabel setText:[formatter stringFromDate:date]];
// This sets the Second Label and formats it in seconds
[formatter setDateFormat:@"ss"];
[timecodeSecondLabel setText:[formatter stringFromDate:date]];
//This sets the Frame Label and formats it in milliseconds
//I need this to be 24 frames per second
[formatter setDateFormat:@"SS"];
[timecodeFrameLabel setText:[formatter stringFromDate:date]];
}
我建议您从
NSDate
中提取毫秒-这是以秒为单位的,因此分数将为您提供毫秒
然后只需使用一个普通格式字符串,使用
NSString
方法stringWithFormat
::。这里有一个处理/Java等价物,很容易重新调整用途
String timecodeString(int fps) {
float ms = millis();
return String.format("%02d:%02d:%02d+%02d", floor(ms/1000/60/60), // H
floor(ms/1000/60), // M
floor(ms/1000%60), // S
floor(ms/1000*fps%fps)); // F
}
NSFormatter+NSDate的批量开销。另外,在我看来,NSDate并没有为简单的东西提供“简单”的微时间情况 Mogga提供了一个很好的指针,下面是一个C/Objective-C变体:
- (NSString *) formatTimeStamp:(float)seconds {
int sec = floor(fmodf(seconds, 60.0f));
return [NSString stringWithFormat:@"%02d:%02d.%02d.%03d",
(int)floor(seconds/60/60), // hours
(int)floor(seconds/60), // minutes
(int)sec, // seconds
(int)floor((seconds - sec) * 1000) // milliseconds
];
}
// NOTE: %02d is C style formatting where:
// % - the usual suspect
// 02 - target length (pad single digits for padding)
// d - the usual suspect
有关此格式的更多信息,请参阅。经过一些尝试后,我仍然不确定如何实现此功能。我已经成功地完成了你的建议,但我似乎遗漏了一整段数学,实际上是每秒24帧的转换。我需要显示的不是每秒100毫秒,而是每秒运行0-23次的数字,并且我需要它与NSTimer完全同步,以便它在每秒结束时实际完成并重新启动。