如何在iOS上定期更新标签(每秒)?

时间:2011-06-03 16:11:52

标签: iphone uikit

我使用的是NSTimer,它会每秒触发一次,并更新一个标签,显示事件发生前的剩余时间。

到目前为止,我的工作正常。问题是当我滚动TableView时,我的Label没有更新,因为MainThread被触摸/滚动事件阻止。

我考虑为Timer创建第二个线程,但无论如何我无法从后台线程更新标签。我不得不在MainThread上使用performSelector ...对它进行排队,它会像之前一样卡住。

滚动时有没有办法更新标签?

3 个答案:

答案 0 :(得分:45)

问题是,当主线程正在跟踪触摸时,不会调用scheduledTimer。您需要在主运行循环中安排计时器。

所以不要做

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateLabel:) userInfo:nil repeats:YES];

使用

NSTimer* timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(updateLabel:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

答案 1 :(得分:0)

试试这个:

    self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateClock) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

答案 2 :(得分:-3)

可以也使用GCD。所以运行

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
    [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateLabel:) userInfo:nil repeats:YES];
});

现在在您的updateLabel方法

- (void) updateLabel:(id) sender {
    NSString *text = @"some text";
    dispatch_sync(dispatch_get_main_queue(), ^{
        label.text = text;
    });
}

这将更新主线程中的标签。