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

Ale*_*ßen 31 iphone uikit

我使用NSTimer每秒触发一次并更新标签,该标签显示事件之前的剩余时间.

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

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

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

DHa*_*ick 46

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

所以不要这样做

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateLabel:) userInfo:nil repeats:YES];
Run Code Online (Sandbox Code Playgroud)

使用

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