2010-07-23 61 views
2

只是測試一些東西....我試圖讓我的視圖的背景顏色切換時,我動搖....但只有當它是目前的某種顏色。爲什麼關於UIColor whiteColor的聲明評估爲false?

-(void)viewDidLoad{  
    self.view.backgroundColor = [UIColor whiteColor]; 
} 


-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{  
    if(event.subtype == UIEventSubtypeMotionShake) 
    { 
     [self switchBackground]; 
    } 
} 


-(void)switchBackground{   
//I can't get the if statement below to evaluate to true - UIColor whiteColor is 
// returning something I don't understand or maybe self.view.backgroundColor 
//is not the right property to be referencing? 

    if (self.view.backgroundColor == [UIColor whiteColor]){ 

     self.view.backgroundColor = [UIColor blackColor]; 
    }  
} 

回答

5

您在這裏比較指針,而不是顏色值。使用-isEqual方法的對象比較:

if ([self.view.backgroundColor isEqual:[UIColor whiteColor]]) 
    ... 

注意查看的backgroundColor屬性與副本屬性定義,因此它不保留指針顏色對象。然而下面這個簡單的例子將工作:

UIColor* white1 = [UIColor whiteColor]; 
if (white1 == [UIColor whiteColor]) 
    DLogFunction(@"White"); // Prints 
+0

完美。非常感謝。將閱讀關於瞭解幕後情況的指針。 – Ben 2010-07-23 15:07:54

0
- (void)viewDidLoad { 
    [super viewDidLoad]; 
    self.view.backgroundColor=[UIColor whiteColor]; 
    if([self.view.backgroundColor isEqual:[UIColor whiteColor]]){ 
     self.view.backgroundColor=[UIColor blackColor]; 
    } else { 
     self.view.backgroundColor=[UIColor whiteColor]; 
    } 
    // your background will be black now 
} 
相關問題