开发者

How to change the background color of any view dynamically?

开发者 https://www.devze.com 2022-12-08 06:28 出处:网络
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 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..

0

精彩评论

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