动态更新UILabel [英] Dynamically Updating a UILabel

查看:109
本文介绍了动态更新UILabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对UILabels有疑问.我什至不确定这是正确的方法,但是我正在尝试更新UILabel以显示从0到24的两个数字,然后循环回到零并再次显示数字顺序.问题是,它需要每1/24秒更新一次UILabel.这是我到目前为止的代码...

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

此代码在运行时成功在控制台中循环输出数字1-24,但是名为"timecodeFrameLabel"的UILabel仅显示03,并且不会更改.

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.

有什么建议吗?

推荐答案

这里有两个问题.首先是您的-updateFpsDisplay方法从0循环到99,每次循环都更改标签.但是,在控件返回到运行循环之前,标签实际上不会被重绘.因此,每0.01秒,您将标签更改100次,然后显示将更新一次.摆脱循环,让计时器告诉您何时更新标签,何时更新标签,只需更新一次.您需要使用计数器变量i并将其设置为实例变量(希望使用更具描述性的名称),而不是该方法的局部变量.

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 variable i and make that an instance variable (hopefully with a more descriptive name) rather than a variable local to that method.

- (void)updateFpsDisplay {
    // the ivar frameCount replaces i
    [timecodeFrameLabel setText:[NSString stringWithFormat:@"0%d", frameCount%24]];
}

第二个问题是100不是24的倍数.当您说99%24 == 3时,这就是标签始终显示"3"的原因.如上所述,更改了代码后,请在方法-updateFpsDisplay中添加一个检查,以使frameCount每次达到0时都将重置,例如:

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 that frameCount is reset each time it hits 0, like:

if (frameCount % 24 == 0) {
    frameCount = 0;
}

这将防止frameCount太大而在某个时候翻转.

That'll prevent frameCount from getting so large that it rolls over at some point.

这篇关于动态更新UILabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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