简体   繁体   中英

How to change the background color of any view dynamically?

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 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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM