viewdidload
{
NSDateFormatter *df = [[[NSDateFormatter alloc] init] init];
[df setDateFormat:@"HH:mm:ss"];
ctime=([df stringFromDate:[NSDate date]]);
NSDate *date1 = [df dateFromString:@"12:44"];`
NSDate *date2 = [df dateFromString:@"20:50"];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
NSString *timeDiff = [NSString stringWithFormat:@"%d:%02d", hours, minutes];
currHour=hours;
currMinute=minutes;
currSeconds=00;
[self start];
}
-(void)start
{
self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}
-(void)timerFired
{
if((currHour>0 || currMinute>0 || currSeconds>=0) && currMinute>=0)
{
if(currSeconds==0)
{
currMinute-=1;
currSeconds=59;
}
else if(currSeconds>0)
{
currSeconds-=1;
}
if(currMinute>-1)
enter code here
[self.timeonelabel setText:[NSString stringWithFormat:@"%d%@%d%@",currHour,@":",currMinute,@":"]];
//[self.hourlabel setText:[NSString stringWithFormat:@"%d%@",currHour,@":"]];
// [self.timeonelabel setText:[NSString stringWithFormat:@"%d%@%d%@",00,@":",currMinute,@":"]];
[self.timetwolabel setText:[NSString stringWithFormat:@"%02d",currSeconds]];
}
else
{
[self.timer invalidate];
}
}
在经过当前时间和结束时间后,计时器应该倒计时到 0。问题是计时器没有运行倒计时,请帮忙。我什至无法在 tableview 中显示计时器倒计时。请帮忙
最佳答案
关于从字符串创建日期,您的代码中有几处错误。首先,您在 NSDateFormatter
中指定的日期格式与您使用的实际格式不匹配 - 一个有秒,另一个没有。这意味着 dateFromString
将返回 nil。此外,您还应该指定一个日期,而不仅仅是时间,否则您无法确定您会得到今天的日期。
最后,您通过在原始变量中提取和跟踪 NSDate
的所有组件,使事情变得过于复杂。我宁愿做这样的事情:
- (void)viewDidLoad {
[super viewDidLoad];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"YYYY/MM/dd HH:mm"];
self.endTime = [df dateFromString:@"2016/02/23 11:00"];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}
-(void)timerFired {
if ([[NSDate date] compare:self.endTime] == NSOrderedAscending) {
NSLog(@"still going");
// enter code here
// Use NSDateComponentsFormatter to show what you need to show
}
else {
NSLog(@"done");
[self.timer invalidate];
}
}
关于ios - 如何在小时和分钟上倒数计时器并在它为 0 时停止, objective-c ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35573340/