我正在尝试显示一个计时器,该计时器从日期开始计算天数、小时、分钟和秒,然后在视图/页面上实时递增。
最好的方法是什么?
最好的方法是阅读日期和时间编程指南以了解如何使用NSDate
、NSCalendar
和NSDateComponents
类。
你可以这样做: -
- (void)viewWillAppear:(BOOL)animated
{
[self start];
[super viewWillAppear:YES];
}
int currentTime;
- (IBAction)start{
currentTime = 0;
lbl=[[UILabel alloc]init];
//creates and fires timer every second
myTimer = [[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES]retain];
}
- (IBAction)stop{
[myTimer invalidate];
myTimer = nil;
}
- (IBAction)reset{
[myTimer invalidate];
lbl.text = @"00:00:00";
}
-(void)showTime{
currentTime++; //= [lbl.text intValue];
//int new = currentTime++;
int secs = currentTime % 60;
int mins = (currentTime / 60) % 60;
int hour = (currentTime / 3600);
int day = currentTime / (60 * 60 * 24);
lbl.text = [NSString stringWithFormat:@"%.2d:%.2d:%.2d:%.2d",day,hour, mins, secs];
NSLog(@"my lable == %@",lbl.text);
NSLog(@"my lable == %@",lbl.text);
}