循环更改UILabel [英] Change UILabel in loop

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

问题描述

我想在循环中2秒后更改UILabel。
但是当前代码在循环结束后将其更改为最后一个值。

I want to change the UILabel after 2 sec in a loop. But current code change it to last value after loop finished.

- (IBAction) start:(id)sender{


   for (int i=0; i<3; i++) {
    NSString *tempStr = [[NSString alloc] initWithFormat:@"%s", @" "];

    int randomNumber = 1+ arc4random() %(3);

    if (randomNumber == 1) {
        tempStr = @"Red";
    }else if (randomNumber == 2) {
        tempStr = @"Blue";
    } else {
        tempStr = @"Green";
    }
       NSLog(@"log: %@ ", tempStr);
       labelsText.text = tempStr;
       [tempStr release];
        sleep(2);

    }
}


推荐答案

您的代码仅在您的功能阻止主线程时将标签更新为最后一个值,因此UI无法更新。要解决该问题,请将更新代码移动到单独的函数,并使用 performSelector:withObject:afterDelay:方法调用它。 (或使用 NSTimer 安排来电)

Your code updates label to last value only as your function blocks main thread so UI cannot get updated. To solve that problem move your updating code to separate function and call it using performSelector:withObject:afterDelay: method. (or schedule calls using NSTimer)

可能的解决方案(当用户点击你的时候你也需要处理这个案例按钮连续几次,但这不应该太难):

Possible solution (you will also need to handle the case when user taps your button several times in a row, but that should not be too difficult):

- (IBAction) start:(id)sender{
    [self updateLabel];
}

- (void) updateLabel{
   static const NSString* allStrings[] = {@"Red", @"Blue", @"Green"};
   static int count = 0;

   int randomNumber = arc4random()%3;
   NSString *tempStr = allStrings[randomNumber];

   NSLog(@"log: %@ ", tempStr);
   labelsText.text = tempStr;

   ++count;
   if (count)
      [self performSelector:@selector(updateLabel) withObject:nil afterDelay:2.0];

}

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

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