开发者

Why does this loop only run once?

Just want the screen to blink blue/red over and over for some time based on an odd or even condition, but it only runs o开发者_StackOverflow中文版nce, instead of 30,000 times. What am I missing?

-(IBAction) changeBackgroundColor:(id)sender
{
    for (int y = 0; y < 30000; y++)
    {

    if(y % 2)
        {
            self.view.backgroundColor = [UIColor blueColor];
            colorView.backgroundColor = [UIColor redColor];  

        } else {

            self.view.backgroundColor = [UIColor redColor];
            colorView.backgroundColor = [UIColor blueColor];   
        }
    }
}


You are "blinking" 30,000 times without ever returning to the iOS main system to give it a chance to display the results of your per blink. You need to blink once, return to iOS, come back, blink again, back to iOS, etc.


The loop runs 30000 times, but the screen is updated only once. You need to drop out to the runloop for changes to UIKit objects to take effect. Probably you want to set up an NSTimer and toggle the background colour within the callback.


If you are trying to get a blinking effect you could (and probably should) use Core Animation.

I answered a similar question here with example code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜