通过(id)发件人访问UIButton

时间:2010-11-06 13:28:10

标签: iphone objective-c uibutton sender

我有以下代码

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

哪个链接到多个按钮。我想隐藏触发此IBAction的按钮。 self.hidden显然不是按钮。

如何隐藏被点按的按钮?发件人。

由于

5 个答案:

答案 0 :(得分:12)

Vladimir和Henrik的答案都是正确的。不要让'id'类型吓到你。它仍然是你的按钮对象,只是编译器不知道类型是什么。因此,除非将其转换为特定类型(Henrik的答案),否则无法在其上引用属性。

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

或者您可以在对象上发送任何消息(调用任何方法),假设您知道类型(您执行的操作,它是一个按钮),而无需投射(Vladimir的答案)。

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

答案 1 :(得分:8)

向发件人发送setHidden邮件:

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

答案 2 :(得分:2)

获取按钮对象(id)作为参数提供

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

答案 3 :(得分:2)

如果你想要防弹演员/消息,请试试这个:

-(IBAction)ATapped:(id)sender{
   // Secure Cast of sender to UIButton
   if ([sender isKindOfClass:[UIButton class]]) {
       UIButton* myButton = (UIButton*)sender;
       myButton.hidden = YES;
   }
}

答案 4 :(得分:0)

并且...如果你想改变按钮的背景颜色,那么正确的代码会是这样的吗?

[sender setBackgroundColor:(NSColor *)redColor];

例如? ...因为它不适合我...