开发者

accessing UIButton by (id)sender

I have the following code

-(IBAction)ATapp开发者_运维百科ed:(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


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];
}


Send setHidden message to sender:

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


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

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


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;
   }
}


And... if you want to change the backgroundcolor of a button, the correct code will be like this?

[sender setBackgroundColor:(NSColor *)redColor];

for example? ... because it is´nt works for my...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜