动态更新 UILabel
我有一个关于 UILabels 的问题。我什至不确定这是实现这一目标的正确方法,但我正在尝试更新 UILabel 以显示从 0 到 24 的两个数字,然后循环回零并再次显示数字序列。问题是,它需要每 1/24 秒更新一次 UILabel。这是我到目前为止的代码...
- (void)viewDidLoad {
fpsTimer = [NSTimer scheduledTimerWithTimeInterval: .01 target: self selector: @selector(updateFpsDisplay) userInfo: nil repeats: YES];
}
- (void)updateFpsDisplay {
for (int i=0; i<100; i++) {
NSLog(@"%d", i%24);
[timecodeFrameLabel setText:[NSString stringWithFormat:@"0%d", i%24]];
}
}
此代码在运行时成功地在控制台中循环打印出数字 1-24,但是名为“timecodeFrameLabel”的 UILabel 仅显示 03 并且不会更改。
有什么建议吗?
I have a question regarding UILabels. I'm not even sure it is the right way to pull this off but I am trying to update a UILabel to display two numbers from 0 to 24 then loop back to zero and display the numer squence again. The catch is, it needs to update the UILabel every 1/24 of a second. Here is the code I have so far...
- (void)viewDidLoad {
fpsTimer = [NSTimer scheduledTimerWithTimeInterval: .01 target: self selector: @selector(updateFpsDisplay) userInfo: nil repeats: YES];
}
- (void)updateFpsDisplay {
for (int i=0; i<100; i++) {
NSLog(@"%d", i%24);
[timecodeFrameLabel setText:[NSString stringWithFormat:@"0%d", i%24]];
}
}
This code successfully prints out the numbers 1-24 in a loop in the console at run-time, However the UILabel named "timecodeFrameLabel" just shows 03 and does not change.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有两个问题。第一个是您的
-updateFpsDisplay
方法从 0 到 99 循环,每次循环都会更改标签。但是,在控制权返回到运行循环之前,标签实际上不会被重绘。因此,每 0.01 秒,您更改标签 100 次,然后显示更新一次。摆脱循环,让你的计时器告诉你何时更新标签,当你更新时,只更新一次。您需要获取计数器变量i
并将其设为实例变量(希望具有更具描述性的名称),而不是该方法的本地变量。第二个问题是 100 不是 24 的倍数。当你说 99 % 24 == 3 时,这就是为什么你的标签总是说“3”。按照上述方式更改代码后,请在方法
-updateFpsDisplay
中添加一个检查,以便frameCount
每次达到 0 时都会重置,例如:
frameCount
变得太大以致于在某个时刻发生翻转。There are two problems here. The first is that your
-updateFpsDisplay
method loops from 0 to 99, changing the label each time through the loop. However, the label won't actually be redrawn until control returns to the run loop. So, every 0.01 seconds, you change the label 100 times, and then the display updates once. Get rid of the loop and let your timer tell you when to update the label, and when you do, update it just once. You'll want to take your counter variablei
and make that an instance variable (hopefully with a more descriptive name) rather than a variable local to that method.The second problem is that 100 is not a multiple of 24. When you say 99 % 24 == 3, which is why your label always says "3". After you've changed your code as described above, add a check to your method
-updateFpsDisplay
so thatframeCount
is reset each time it hits 0, like:That'll prevent
frameCount
from getting so large that it rolls over at some point.