如何在 iOS 上定期更新标签(每秒)? [英] How update a label periodically on iOS (every second)?

查看:13
本文介绍了如何在 iOS 上定期更新标签(每秒)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use a NSTimer which fires every second and updates a label which displays the remaining time until an event.

到目前为止我工作得很好.问题是当我滚动 TableView 时,我的标签没有更新,因为 MainThread 被触摸/滚动事件阻塞.

I works fine so far. The problem is while I am scrolling the TableView my Label does not update, because the MainThread is blocked by the touch/scroll event.

我曾考虑为 Timer 创建第二个线程,但无论如何我无法从后台线程更新标签.我不得不将它与 performSelector... 放在 MainThread 上,它会像以前一样卡住.

I thought about creating a second thread for the Timer but I couldn't update the label from a background thread anyways. I had to queue it with performSelector... on the MainThread where it would stuck like before.

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

Is there any way to update the label while scrolling?

推荐答案

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

The problem is that a scheduledTimer will not get called while the main thread is tracking touches. You need to schedule the timer in the main run loop.

所以不要这样做

[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];

这篇关于如何在 iOS 上定期更新标签(每秒)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆