Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing UIButton by (id)sender

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

like image 658
some_id Avatar asked Nov 06 '10 13:11

some_id


4 Answers

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];
}
like image 124
shanezilla Avatar answered Nov 05 '22 12:11

shanezilla


Send setHidden message to sender:

-(IBAction)ATapped:(id)sender{
   //want some way to hide the button which is tapped
   [sender setHidden:YES];
}
like image 40
Vladimir Avatar answered Nov 05 '22 11:11

Vladimir


Your getting the button object (id) provided as a parameter

-(IBAction)ATapped:(id)sender{
   // Possible Cast
   UIButton* myButton = (UIButton*)sender;
   myButton.hidden = YES;
}
like image 30
Henrik P. Hessel Avatar answered Nov 05 '22 11:11

Henrik P. Hessel


If you want bullet proof cast/messaging, try this:

-(IBAction)ATapped:(id)sender{
   // Secure Cast of sender to UIButton
   if ([sender isKindOfClass:[UIButton class]]) {
       UIButton* myButton = (UIButton*)sender;
       myButton.hidden = YES;
   }
}
like image 2
Erdemus Avatar answered Nov 05 '22 10:11

Erdemus