通过计时器更新UILabel无法正常工作

时间:2012-01-17 22:17:40

标签: iphone objective-c ios

我正在尝试更新从用户生日到晚些时候倒计时的UILabel。我正在尝试更新标签,以便他们可以看到它倒计时但似乎无法使其正常工作。建议表示赞赏!

这是我制作计时器的地方:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFormatted:) userInfo:nil repeats:NO];
}

这里是我获取实际倒计时信息的地方......

- (NSString *)timeFormatted:(int)totalSeconds
{       
    NSTimeInterval theTimeInterval = [self numberOfSecondsToLive];

    NSCalendar *sysCalendar = [NSCalendar currentCalendar];

    NSDate *date1 = [[NSDate alloc] init];
    NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1]; 

    unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | NSSecondCalendarUnit;

    NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];

  _numberofSeconds.text = [NSString stringWithFormat:@" %dyears:%dMonths:%ddays:%dhour:%dminutes:%dseconds",[conversionInfo year],[conversionInfo month], [conversionInfo day], [conversionInfo hour], [conversionInfo minute], [conversionInfo second]];

    [date1 release];
    [date2 release];
 } 

它会显示正确的倒计时信息,但不会更新它。

提前谢谢!

2 个答案:

答案 0 :(得分:5)

您启动了repeats:NO计时器,希望repeats:YES让计时器重复。

答案 1 :(得分:3)

也许您想在此行中将repeats设置为YES而不是NO

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFormatted:) userInfo:nil repeats:NO];

另一方面,这一行是错误的:

- (NSString *)timeFormatted:(int)totalSeconds

应该是:

- (void)timeFormatted:(NSTimer *)timer