How to change the background color of a view dynamically? Do I set a timer and assign the background color property of the view to change in a loop?
How开发者_JS百科 to achieve this functionality?
Somewhere in your code (viewDidAppear is a good spot)
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5 // seconds
target:self
selector:@selector(changeBackground:)
userInfo:nil
repeats:YES];
A method in your class:
- (void)changeBackground:(NSTimer *)timer {
if (iWantToCancelTimer) {
[timer invalidate];
}
self.view.backgroundColor = [UIColor whateverColor];
}
This will be an abrupt change so you will probably want to make an animation, but this is a different question.
Sounds like you just want your view to change background colors every x amount of time. For that, yes for the view in question you can set a timer up and change the background c olor everytime it fires (you can maybe randomly generate some RGB values).
You can use + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds target:(id)target selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)repeats to set a timer to a selector and in there you can change the view background...keep in mind that UIKit isnt thread s afe so if you have the timer running in another thread you should change the views background on the main thread..
精彩评论