objective c - Background color


Keywords:objective  c 


Question: 

This is a simple question, but I have looked for the answer without luck.

I want to access the background color of a button to save it into a variable and be able to access it later.

So, I have got an instance property declared in the view controller:

@property UIColor *variable;

and, in my method:

-(IBAction)buttonPressed:(id)sender {
    variable = sender.backgroundColor;
}

but I get the error:

property backgroundcolor not found in object of type _strong id warning.

Where's the mistake?


1 Answer: 

You have three options:

  1. Change the sender property from id to UIButton *.

    - (IBAction)buttonPressed:(UIButton *)sender {
        self.variable = sender.backgroundColor;
    }
    
  2. Call the backgroundColor getter method instead of using the backgroundColor property.

    - (IBAction)buttonPressed:(id)sender {
        self.variable = [sender backgroundColor];
    }
    
  3. Use a cast on sender.

    - (IBAction)buttonPressed:(id)sender {
        self.variable = ((UIButton *)sender).backgroundColor;
    }
    

The main issue you have is that you can't use property references on objects of type id.