简体   繁体   中英

How can I force iOS to change background color immediately?

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

I need a blinking background, ie 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?

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

}

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

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