如何经常更新UILabel?

时间:2013-04-02 12:37:32

标签: uilabel

我想经常更新标签文字,但似乎无效。

for (int i = 0; i <100; i++)
{
 mylabel.text =[NSString stringWithFormat:@"%d", i];
}

有人建议给我一个想法吗?我想。也许,我们应该在多个线程中更新文本标签。

3 个答案:

答案 0 :(得分:1)

观看是最好的例子,希望它会帮助你....

int second,minute;    //set second = 0 and minute = 0
[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];

- (void)updateCounter:(NSTimer *)theTimer {
    second++;

    if(second < 60)
        {
        if (second < 10) 
            {
            timerLbl.text = [NSString stringWithFormat:@"00:0%d", second];
            }
        else
            {
            timerLbl.text = [NSString stringWithFormat:@"00:%d",second];
            }
        }
    else
        {
        minute = second / 60;
        int sec = second % 60;

        if (minute < 10 && sec < 10) 
            {
            timerLbl.text = [NSString stringWithFormat:@"0%d:0%d", minute, sec];
            }
        if(minute < 10 && sec >= 10)
            {
            timerLbl.text = [NSString stringWithFormat:@"0%d:%d", minute, sec];
            }
        if (minute >= 10 && sec < 10) 
            {
            timerLbl.text = [NSString stringWithFormat:@"%d:0%d", minute, sec];
            }
        if(minute >= 10 && sec >= 10)
            {
            timerLbl.text = [NSString stringWithFormat:@"%d:%d", minute, sec];
            }
        }
}

答案 1 :(得分:1)

Add below code in viewDidLoad
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5f
                                     target:self
                                   selector:@selector(showTime)
                                   userInfo:NULL
                                    repeats:YES];

- (void)showTime
{
    NSDate *now=[NSDate date];
    NSDateFormatter *dateFormatter=[NSDateFormatter new];
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    timeLabel.text=[dateFormatter stringFromDate:now];
}

希望这个答案能帮到你......

答案 2 :(得分:1)

定期使用NSTimer并调用打印标签的方法,假设

[NSTimer scheduledTimerWithTimeInterval:2.0
target:self
selector:@selector(targetMethod:)
userInfo:nil
repeats:Yes];
目标方法中的

在文本上打印标签

-(void)targetMethod:(NSTimer *)timer{
NSDate* date = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@" HH:MM:SS"];
NSString* str = [formatter stringFromDate:date];
label.text = str;
}

试试这肯定会有效