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.

  • Get the color a pixel on the screen in objective-c cocoa app
  • Change UIPicker color
  • Color ouput with Swift command line tool
  • Displaying PDF documents on iPad - Color Problems
  • Color detection at a distance (Swift)
  • Want to change a particular color inside an image with another color - iPhone
  • 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];
        }];
    
     [UIView commitAnimations];
    
    }
    

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

    2 Solutions Collect From Internet About “UIView backgroundColor color cycle”

    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.