accessing UIButton by (id)sender

some_id picture some_id · Nov 6, 2010 · Viewed 18.3k times · Source

I have the following code

-(IBAction)ATapped:(id)sender{
//want some way to hide the button which is tapped
self.hidden = YES;
}

Which is linked to multiple buttons. I want to hide the button which triggered this IBAction. self.hidden is obviously not the button.

How do I hide the button which was tapped? The sender.

Thanks

Answer

shanezilla picture shanezilla · Nov 6, 2010

Both Vladimir and Henrik's answers would be correct. Don't let the 'id' type scare you. It's still your button object it's just that the compiler doesn't know what the type is. As such you can't reference properties on it unless it is cast to a specific type (Henrik's answer).

-(IBAction)ATapped:(id)sender{
   // Possible Cast
   UIButton* myButton = (UIButton*)sender;
   myButton.hidden = YES;
}

Or you can send any message (call any method) on the object, assuming YOU know the type (which you do, it's a button), without having to cast (Vladimir's answer).

-(IBAction)ATapped:(id)sender{
   //want some way to hide the button which is tapped
   [sender setHidden:YES];
}