Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 按00:00:00格式进行计数_Objective C_Cocoa Touch - Fatal编程技术网

Objective c 按00:00:00格式进行计数

Objective c 按00:00:00格式进行计数,objective-c,cocoa-touch,Objective C,Cocoa Touch,一旦按下iAction,我需要一个计数的计数器 但是以这种形式 00:00:00 小时:分:秒 这是迄今为止的代码: -(void)countUp { mainInt += 1; seconds.text = [NSString stringWithFormat:@"%02d", mainInt]; } 这只以00格式计算 谢谢你的帮助 只需做适当的数学运算,将计数分解为各个组成部分: NSString *timeString = [NSString stringWithF

一旦按下iAction,我需要一个计数的计数器

但是以这种形式

00:00:00 小时:分:秒

这是迄今为止的代码:

-(void)countUp {

    mainInt += 1;
    seconds.text = [NSString stringWithFormat:@"%02d", mainInt];

}
这只以00格式计算


谢谢你的帮助

只需做适当的数学运算,将计数分解为各个组成部分:

NSString *timeString = [NSString stringWithFormat:@"%02d:%02d:%02d",
                                                  totalSeconds/3600,        // hours
                                                  (totalSeconds/60)%60,     // minutes
                                                  totalSeconds%3600]        // seconds
为了可读性,最好用宏或函数替换内联数学,例如:

#define secondsPerMinute 60
#define minutesPerHour 60

int hours(int secs) {
    return secs/(minutesPerHour * secondsPerMinute);
}

int minutes(int secs) {
    return (secs/secondsPerMinute) % minutesPerHour;
}

int seconds(int secs) {
    return secs % (minutesPerHour * secondsPerMinute);
}

// ...
NSString *timeString = [NSString stringWithFormat:@"%02d:%02d:%02d",
                                                  hours(totalSeconds),
                                                  minutes(totalSeconds),
                                                  seconds(totalSeconds)];
通常,在实现这种显示时,您不希望冒号随着所用时间的变化而跳转。许多字体都有固定宽度的数字,所以这并不总是一个问题,但您可能希望在小时、分钟和秒之间使用三个单独的标签,在这三个标签之间使用不变的冒号标签

上述数学的另一种方法是将秒、分钟和小时存储在三个变量中,而不是一个变量中,只需小心地增加分钟数,并在秒数达到60时重置秒数,以此类推。要使其更易于使用,请将其封装在类中,如:

@interface Time : NSObject {
    int seconds;
    int minutes;
    int hours;
}
- (void)countUp;
- (NSString*)timeString;
@end;