将参数传递给 addTarget:action:forControlEvents [英] Passing parameters to addTarget:action:forControlEvents
问题描述
我正在使用 addTarget:action:forControlEvents,如下所示:
I am using addTarget:action:forControlEvents like this:
[newsButton addTarget:self
action:@selector(switchToNewsDetails)
forControlEvents:UIControlEventTouchUpInside];
我想将参数传递给我的选择器switchToNewsDetails".我唯一能做的就是通过以下方式传递(id)发件人:
and I would like to pass parameters to my selector "switchToNewsDetails". The only thing I succeed in doing is to pass the (id)sender by writing:
action:@selector(switchToNewsDetails:)
但我试图传递像整数值这样的变量.这样写是行不通的:
But I am trying to pass variables like integer values. Writing it this way doesn't work :
int i = 0;
[newsButton addTarget:self
action:@selector(switchToNewsDetails:i)
forControlEvents:UIControlEventTouchUpInside];
这样写也行不通:
int i = 0;
[newsButton addTarget:self
action:@selector(switchToNewsDetails:i:)
forControlEvents:UIControlEventTouchUpInside];
任何帮助将不胜感激:)
Any help would be appreciated :)
推荐答案
action:@selector(switchToNewsDetails:)
您不要在此处将参数传递给 switchToNewsDetails:
方法.您只需创建一个选择器,使按钮能够在发生某些操作时调用它(在您的情况下进行修改).控件可以使用 3 种类型的选择器来响应动作,它们都有预定义的参数含义:
You do not pass parameters to switchToNewsDetails:
method here. You just create a selector to make button able to call it when certain action occurs (touch up in your case). Controls can use 3 types of selectors to respond to actions, all of them have predefined meaning of their parameters:
无参数
action:@selector(switchToNewsDetails)
带1个参数指示发送消息的控件
with 1 parameter indicating the control that sends the message
action:@selector(switchToNewsDetails:)
用2个参数表示发送消息的控件和触发消息的事件:
With 2 parameters indicating the control that sends the message and the event that triggered the message:
action:@selector(switchToNewsDetails:event:)
目前尚不清楚您到底要做什么,但考虑到您想为每个按钮分配一个特定的详细信息索引,您可以执行以下操作:
It is not clear what exactly you try to do, but considering you want to assign a specific details index to each button you can do the following:
- 为每个按钮设置一个等于所需索引的标签属性
在
switchToNewsDetails:
方法中,您可以获得该索引并打开相应的详细信息:
- set a tag property to each button equal to required index
in
switchToNewsDetails:
method you can obtain that index and open appropriate deatails:
- (void)switchToNewsDetails:(UIButton*)sender{
[self openDetails:sender.tag];
// Or place opening logic right here
}
这篇关于将参数传递给 addTarget:action:forControlEvents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!