简体   繁体   English

如何动态更改任何视图的背景色?

[英]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) 在代码中的某个位置(viewDidAppear是一个不错的选择)

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. 听起来就像您只希望视图每x时间更改背景颜色。 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). 为此,可以为该视图设置一个计时器,并在每次触发时更改背景色(您可以随机生成一些RGB值)。

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.. 您可以使用+(NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds目标:(id)目标选择器:(SEL)aSelector userInfo:(id)userInfo重复:(BOOL)重复将计时器设置为选择器,您可以在其中设置计时器更改视图背景...请记住,UIKit不是线程安全的,因此,如果您在另一个线程中运行计时器,则应在主线程上更改视图背景。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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