Cra*_*Dev 36 objective-c sender ibaction
在一些IBAction
我看到:
- (IBAction)pushButton:(id)sender;
Run Code Online (Sandbox Code Playgroud)
该(id)sender
什么时候使用它?
Ahm*_*ali 62
Matt Galloway (id) sender
在iPhone Dev SDK论坛上描述了操作的含义:
(id)sender是将消息发送到该选择器的对象.就像在委托函数中,您将控件传递给函数等.
如果您有两个调用该选择器的对象并且想要区分它们,则可以使用它.当然,您可以使用两种不同的功能,但使用一个功能通常更清晰,代码重复更少.
有关更多详细信息,请参阅 UIControl类参考.
例如,UITextField有一个委托,当UITextField编辑结束时触发:
-(IBAction) editingEnded:(id) sender {
// the cast goes here, lets assume there's more than one UITextfield
// in this Owner and you want to know which one of them has triggered
// the "editingEnded" delegate
UITextField *textField= (UITextField*)sender;
if(textfield == iAmTheLastTextField)
{
// for example login now.
[self login];
}
}
Run Code Online (Sandbox Code Playgroud)
fuz*_*uzz 36
(id)sender is the object which sent the message to that selector.
Run Code Online (Sandbox Code Playgroud)
代码示例:
- (IBAction)submitButton:(id)sender {
UIButton *button = (UIButton *)sender;
[button setEnabled:NO];
[button setTitle:@"foo" forState:UIControlStateDisabled];
}
Run Code Online (Sandbox Code Playgroud)
"sender"是变量的名称.
"(id)"表示变量的类型是"id",表示"任何对象"(如果需要,可以将其视为对象层次结构的顶部
方法的名称是pushButton:并且需要任何类型的1个参数.
此方法将链接到UI上的按钮.此UI的代理将接收此调用,并将引用已进行调用的UIButton.有时您不需要它,有时您需要访问该UIButton才能更改其属性.