假设我已经在我的应用程序中制作了一个数字时钟,我希望有2个标签秒,2个标签分钟和2个标签几小时,所有标签必须同步运行才能给我正确的响应。我想我必须使用NSDateFormatter并将日期格式设置为每个标签,因此它可以代表将在六个不同标签中一起显示的六位数字之一。有谁知道我怎么做到这一点?
这有点难以解释,我希望这对你们有任何意义。只要问你是否想要进一步解释这个问题。
答案 0 :(得分:1)
您应该查看NSDateComponent和programming guide。
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [currentCalendar components:unitFlags fromDate:[NSDate date]];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSInteger second = [components second];
然后,如果您想将组件分成两个标签,您可以将它们转换为字符串并获得char
索引0
和1
(前提是有两位数字)
修改强>
在两个标签上分割组件的2位数的示例:
UILabel* label1;
UILabel* label2;
NSInteger hour = 2;
// so that it is always 2 (or more) characters long
NSString* s = [NSString stringWithFormat:@"%*d", 2, hour];
NSLog(@"<%@>", s);
NSString* s1 = [s substringToIndex:1];
NSString* s2 = [s substringFromIndex:1];
label1.text = s1;
label2.text = s2;