【问题标题】:NSTimer not working accurately.NSTimer 无法正常工作。
【发布时间】:2015-03-07 05:55:51
【问题描述】:

我正在尝试制作一个倒数计时器,但是我正在为我的代码而苦苦挣扎。我有一个 UIDatePicker 来选择倒计时的日期,但是每次我尝试倒计时时,秒数都从 54 秒开始,而不是调整到设备的实际时间。代码非常简单明了,但我很难弄清楚。

- (IBAction)startCountdown:(id)sender {
if (ti == 0||ti <= 0) {
    [self stopCountdown:self];
}

//Set up a timer that calls the updateTime method every second to update the label
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(updateTime)
                                       userInfo:nil
                                        repeats:YES];
}
-(void)updateTime{


//Get the time left until the specified date and convert time into seconds.
NSInteger ti = ((NSInteger)[self.datePicker.date timeIntervalSinceNow]); //this is the key part of the code.
NSInteger seconds = ti % 60;
NSInteger minutes = (ti / 60) % 60;
NSInteger hours = (ti / 3600) % 24;
//NSInteger days = (ti / 86400);

//Update the lable with the remaining time
//self.countdownLabel.text = [NSString stringWithFormat:@"%02i days %02i hrs %02i min %02i sec", days, hours, minutes, seconds];
self.countdownLabel.text = [NSString stringWithFormat:@"%02i hrs %02i min %02i sec", hours, minutes, seconds];

}

请帮帮我,不胜感激!

提前谢谢各位朋友!!

【问题讨论】:

    标签: objective-c nstimer countdown uidatepicker nsinteger


    【解决方案1】:

    有更简单的方法可以提取时间单位,以防止计算错误。看看[NSCalendar components:fromDate:toDate:options:]

    它可能变成:

    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit components = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *diff = [calendar components:components fromDate:self.datePicker.date toDate:now options:0];
    NSInteger seconds = [diff second];
    NSInteger minutes = [diff minute];
    NSInteger hours = [diff hour];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      • 2016-12-01
      • 1970-01-01
      • 2016-09-01
      • 2012-07-11
      • 2018-04-08
      • 2017-04-20
      相关资源
      最近更新 更多