0

Hi i am a bit lost with what I am trying to do. I can easily switch the color of a view controller by making a property of the view itself and then using something like:

@property (strong, nonatomic) IBOutlet UIView *viewController;
 self.viewController.backgroundColor = [UIColor redColor]; //first color
self.viewController.backgroundColor = [UIColor whiteColor]; //second color

Now lets say that I wanted a particular view to repeatedly change back and forth between 2 colors every second. How could I do this?

Thanks in Advance

1 Answers1

0

You should look into NSTimer for this...

// In viewDidLoad or wherever you want to start alternating...
NSTimer *myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerListener) userInfo:nil repeats:YES];

- (void)timerListener {
    if (viewIsFirstColor) {
        // Code to switch colors
    } else {
        // Code to switch colors
    }
}

You may want to invalidate this timer when you're done with it...

Uxonith
  • 1,602
  • 1
  • 13
  • 16
  • The only thing I am having some trouble with is viewIsFirstColor what is that variable supposed to be so that it switches every second? that is the only thing I am not understanding. – user3007683 May 31 '14 at 00:09
  • Try this (self.viewController.backgroundColor == [UIColor redColor] ) instead of (viewIsFirstColor). – JScarry May 31 '14 at 00:40
  • You should use `-isEqual:` instead of `==` to compare Objective-C objects. – Zev Eisenberg May 31 '14 at 04:13
  • Oh sorry about that `viewIsFirstColor`, that was just a placeholder for your logic to determine if view was the first color :) – Uxonith Jun 02 '14 at 23:03
  • This worked the code used for the function was: -(void)timerListener { if ([self.mainViewController.backgroundColor isEqual:[UIColor colorWithRed:249.0/255.0 green:70.0/255.0 blue:28.0/255.0 alpha:1]]) { self.mainViewController.backgroundColor = [UIColor whiteColor]; } else if([self.mainViewController.backgroundColor isEqual:[UIColor whiteColor]]){ self.mainViewController.backgroundColor = [UIColor colorWithRed:249.0/255.0 green:70.0/255.0 blue:28.0/255.0 alpha:1]; // Code to switch colors } } – user3007683 Jun 03 '14 at 02:13