简体   繁体   English

UIButton图像在“for”循环中不会发生变化

[英]UIButton Image doesn't changes in a “for” loop


i have a question: 我有个问题:
I designed my GUI without the InterfaceBuilder, 我设计的GUI没有InterfaceBuilder,
now i want change the image of a button for a short period of time, but it won't change, until the whole for-loop has finished. 现在我想在短时间内更改按钮的图像,但是在整个for循环完成之前它不会改变。 What am i doing wrong? 我究竟做错了什么?

    for (size_t i=0; i< 100; ++i){
      switch (variable) {
        case 0:
          [self changeRedButtonToWhite: redButton];
        break;
        case 1:
        ....
      }
    }

-(IBAction) changeRedButtonToWhite: (id)sender{
    [sender setBackgroundImage: whiteImage forState: UIControlStateNormal];
}

You can't use a for loop to do this, you should try using an NSTimer instead. 您不能使用for循环来执行此操作,您应该尝试使用NSTimer The UI isn't refreshed while there is a loop going on inside the main thread. 在主线程内部发生循环时,UI不会刷新。

@Luzal's explanation is correct. @ Luzal的解释是正确的。 You're setting the background color of the button, but that only causes the button to be marked as needing to be redrawn. 您正在设置按钮的背景颜色,但这只会导致按钮被标记为需要重绘。 The redrawing doesn't happen (at least) until execution returns to the run loop, and that can't happen until your for loop finishes. 重新绘制不会发生(至少),直到执行返回到运行循环,并且在for循环结束之前不会发生。

We can't tell from the code you posted what else you're doing in you for loop, but if you're using it as the delay mechanism and then changing the button color back to red when, say, variable hits 99, that's not a great plan anyway. 我们无法从你发布的代码中看出你在循环中做了什么,但如果你将它用作延迟机制,然后将按钮颜色改回红色,比如variable命中99,那就是反正不是一个好计划。 You can use NSTimer to manage the duration of the color change, or -performSelector:afterDelay:, or use Core Animation. 您可以使用NSTimer来管理颜色更改的持续时间,或使用-performSelector:afterDelay:或使用Core Animation。

将for循环放在后台线程上并在主线程上调用-changeRedButtonToWhite。

Can you not do the following? 你能不能做到以下几点?

Add all your buttons to an NSMutableArray , or just use NSArray if your not planning on adding more buttons to it after it has been allocated. 将所有按钮添加到NSMutableArray ,或者如果您没有计划在分配后添加更多按钮,则只需使用NSArray

NSMutableArray *buttonsArray = [[NSMutableArray alloc] initWithObjects:button1, button2, button3, nil]; //and so on....

and then.... 接着....

for(UIButton *button in buttonsArray){
     [button setBackgroundImage: whiteImage forState: UIControlStateNormal];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM