我该如何强制iOS立即更改背景颜色?

3
有没有办法立即更改窗口的背景颜色?
我需要一个闪烁的背景,即红/绿色在一秒钟的间隔内闪烁。正如我所看到的,背景颜色不会立即更改,而只有在离开函数时才会更改。
是否有任何方法强制系统立即更改并重新绘制窗口的背景?

1
如果您觉得答案正确,请接受它。这样其他人就可以轻松参考它了。 :) - Naveen Thunga
2个回答

6
- (void)viewDidLoad 
{
    [super viewDidLoad];
    flag = YES;
    NSTimer *mTimer = [NSTimer scheduledTimerWithTimeInterval:.5
                                                       target:self 
                                                     selector:@selector(changeColor)
                                                     userInfo:nil
                                                      repeats:YES];  
}

- (void)changeColor
{
    if (flag == YES)
    {
        self.view.backgroundColor = [UIColor redColor];
        flag = NO;
        return;
    }
    self.view.backgroundColor = [UIColor blueColor];
    flag = YES;

}

4

Naveen已经做了一个不错的开始,但你可以通过为颜色变化添加动画效果来展示更高级的技巧。

- (void)viewDidLoad {
    [super viewDidLoad];

    // Set up the initial background colour
    self.view.backgroundColor = [UIColor redColor];

    // Set up a repeating timer.
    // This is a property,
    self.changeBgColourTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(changeColour) userInfo:nil repeats:YES];
}

- (void) changeColour {
    // Don't just change the colour - give it a little animation. 
    [UIView animateWithDuration:0.25 animations:^{
        // No need to set a flag, just test the current colour.
        if ([self.view.backgroundColor isEqual:[UIColor redColor]]) {
            self.view.backgroundColor = [UIColor greenColor];
        } else {
            self.view.backgroundColor = [UIColor redColor];
        } 
    }];

    // Now we're done with the timer.
    [self.changeBgColourTimer invalidate];
    self.changeBgColourTimer = nil;
}

你在哪里定义changeBgColourTimer? - xmux
代码片段的第九行,它以self.changeBgColourTimer = ...开头。 - Abizern
我遇到了这个错误:在类型为“Viewcontroller”的对象上找不到属性“changeBgColourTimer”,很抱歉我是个新手,只是在尝试代码。 - xmux
1
在你的视图控制器头文件(.h)中添加以下语句:@property (nonatomic, strong) NSTimer *changeBgColourTimer; - guenis
1
在这种情况下,我会将其放在实现文件中的类扩展中。这不是需要在公共接口中的属性。 - Abizern
我试图每1秒钟改变一次颜色,所以我将它设置为0.1,但绿色颜色仅保持不变,不会改变成其他任何颜色... - xmux

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接