2011-06-09 55 views
3

是否有任何方法可以立即更改窗口的背景顏色?如何強制iOS立即更改背景顏色?

我需要一個閃爍的背景,即紅色/綠色以一秒的間隔閃爍。正如我所看到的,背景顏色不會立即改變,但只有當功能被留下時。

有沒有辦法強制系統改變它並立即重畫窗口的背景?

+1

如果您覺得答案是正確的,請接受它。以便其他人可以輕鬆地參考。 :) – 2011-06-09 11:11:46

回答

4

納文給了一個很好的第一次啓動,但您可以通過動畫顏色變化顯示出多一點的類。

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

你如何/在哪裏定義changeBgColourTimer? – xmux 2013-04-24 20:44:32

+0

第9行代碼片段,它開始'self.changeBgColourTimer = ...' – Abizern 2013-04-24 21:18:55

+0

我得到這個錯誤:Property'changeBgColourTimer'找不到'Viewcontroller'類型的對象,對不起,我是完全新手,只是嘗試在您的代碼 – xmux 2013-04-24 21:26:07

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; 

}