Why does this statement about UIColor whiteColor evaluate to false?
Just testing something out....I'm trying to get the background colour of my view to switch when I shake it....but only if it is currently a certain colour.
-(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 == 开发者_StackOverflow中文版[UIColor whiteColor]){
self.view.backgroundColor = [UIColor blackColor];
}
}
You are comparing pointers here, not color values. Use -isEqual method for objects comparison:
if ([self.view.backgroundColor isEqual:[UIColor whiteColor]])
...
Note that view's backgroundColor
property is defined with copy attribute so it does not preserve the pointer to color object. However the following simple example will work:
UIColor* white1 = [UIColor whiteColor];
if (white1 == [UIColor whiteColor])
DLogFunction(@"White"); // Prints
- (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
}
精彩评论