views:

89

answers:

2

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 == [UIColor whiteColor]){

        self.view.backgroundColor = [UIColor blackColor];
    }    
}
+4  A: 

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
Vladimir
works perfectly. many thanks. will read up about pointers to learn what is going on behind the scenes.
Ben
A: 
- (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
}
sugar