How can I force iOS to change background color imm

2019-05-14 11:11发布

问题:

Is there any way to change the background color of a window immediately?

I need a blinking background, i.e. red/green blinking in an interval of a second. As i see, the background color will not change immediately, but only when function is left.

Is there any way to force the system to change it and redraw the window's background immediately?

回答1:

Naveen has given a good first start, but you can show a little more class by animating the colour change.

- (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;
}


回答2:

- (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;

}