开发者

UIView backgroundColor color cycle

First of all, I am new to this Xcode/Objective-C thing, so go easy on me! :) I made a test app that, by pressing some buttons, the background changes. I have a red, blue, green, white, black and revive button.

I made the app change the color of the backgrnd by pressing all the color buttons. However, I want to make the app cycle through the colors, say 100 times very fast when pressing the Revive button. For some reason, it doesnt work.

The following is the code that isn't working:

Using the code below, only changes to the last color.

- (IBAction)Revive:(id)sender {

    for (int y=0; y < 100; y++) {
    view1.backgroundColor = [UIColor redColor];
    view1.backgroundColor = [UIColor greenColor];
    view1.backgroundColor = [UIColor blueColor];
    view1.backgroundColor = [UIColor whiteColor];
    view1.backgroundColor = [UIColor blackColor];
                                }  
}

Using the code below, whitout the loop, the app fades from white to black

- (IBAction)Revive:(id)sender {

    [UIView animateWithDuration:0.2 animations:^{
    view1.backgroundColor = [UIColor redColor];
    view1.backgroundColor = [UIColor greenColor];
    view1.backgroundColor = [UIColor blueColor];
    view1.backgroundColor = [UIColor whiteColor];
    view1.backgroundColor = [UIColor blackColor];
   开发者_StackOverflow中文版 }];

 [UIView commitAnimations];

}

Anyone knows why this is happening and a solution to my problem?


This will work:

- (void) doBackgroundColorAnimation {
    static NSInteger i = 0;
    NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], [UIColor whiteColor], [UIColor blackColor], nil];

    if(i >= [colors count]) {
        i = 0;
    }

    [UIView animateWithDuration:2.0f animations:^{
        self.view.backgroundColor = [colors objectAtIndex:i];           
    } completion:^(BOOL finished) {
        ++i;
        [self doBackgroundColorAnimation];
    }]; 

}


The view needs time to redraw, in the first example you have you set the backgroundcolor, but the view doesn't redraw untill you are done with that method. With the animation its the same thing, its like saying the following:

int x = 0;
x = 5;
x = 6;
// why is x 6 ? :(

I would use an NSTimer to loop through the colors.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜