iOS-在操作中传递参数:@selector()

iOS-在操作中传递参数:@selector(),ios,objective-c,methods,action,selector,Ios,Objective C,Methods,Action,Selector,我正在以编程方式向UITableViewCell添加一个按钮。按下按钮时要运行的方法是-(void)quantityDown:(id)发送方行号:(int)rowNum,其中rowNum是按钮出现的行 将目标添加到按钮时,Xcode会自动完成以下操作: [buttonDown addTarget:self action:@selector(quantityDown:rowNumber:) forControlEvents:UIControlEventTouchUpInside]; 但无论我尝试

我正在以编程方式向UITableViewCell添加一个按钮。按下按钮时要运行的方法是
-(void)quantityDown:(id)发送方行号:(int)rowNum
,其中
rowNum
是按钮出现的行

将目标添加到按钮时,Xcode会自动完成以下操作:

[buttonDown addTarget:self action:@selector(quantityDown:rowNumber:) forControlEvents:UIControlEventTouchUpInside];
但无论我尝试什么,我都无法将行号传递到方法中。我假设代码的相关部分如下所示

action:@selector(quantityDown:rowNumber:indexPath.row)
但这并不能解决问题。我见过其他类似的东西

action:@selector(quantityDown:)rowNumber:indexPath.row

但两者都不起作用。我不需要传递第一个参数,只需要传递行号。我还尝试过定义方法,如
-(void)quantityDown:(int)rowNum
,然后编写选择器,如:

action:@selector(quantityDown:indexPath.row)
但这也不起作用

想法


提前感谢。

将每个按钮标记设置为
indexPath.row
。然后只需声明函数:

- (void)quantityDown:(id)sender
在该方法中,请执行以下操作:

UIButton *btn = (UIButton *)sender;
添加如下目标:

[buttonDown addTarget:self action:@selector(quantityDown:) forControlEvents:UIControlEventTouchUpInside];

btn.tag
可以获得行号。希望这有帮助。:)

为什么不创建一个
自定义UIButton类
并将对象作为属性

见下文

“MyButton.h”

“MyButton.m”

现在将
MyButton类
分配给单元格中的实际按钮/或初始化自定义按钮,而不是普通的
UIButton类
,并直接分配对象

在您的
iAction
中,其中
sender=MyButton

- (void) quantityDown:(id)sender{
   MyButton *btn  = (MyButton *)sender;
   //You get the object directly
   btn.obj;
}
通过这种方式,您实际上可以轻松访问所需的任意多个属性。它在其他实现中也很有用


希望有帮助。

按钮只能携带一个输入,因此请保持发件人和
rowNum
相同,以便轻松处理 “以单元格换行”方法

UIButton *b = [UIButton buttonWithType:UIButtonTypeContactAdd];
b.tag = indexPath.row;
[b addTarget:self action:@selector(quantityDown:) forControlEvents:UIControlEventTouchUpInside];
你的方法

 - (void)quantityDown:(id)sender  
    {    
       NSLog(@"%d", sender.tag);  
    }

希望这将有助于…

刚刚找到的线程。我会试试的。是的,就是这样。我设置了
buttonDown.tag=indexPath.row
,然后在该方法中,我可以通过
UIButton*clicked=(UIButton*)sender访问它
然后将一个整数设置为单击的
。标记
您不能在按钮单击中传递值。可能的方法是从按钮发送器中查找值,或者在单击按钮时调用另一个方法。第一个是正确的方法。正如我在对原始问题的评论中提到的那样,这就是我最终所做的。谢谢欢迎光临。是的,我现在看到了。可能是我正忙着输入答案这是一个很好的解决方案。如果我需要更多的数据,而不仅仅是行数,那么我肯定会这样做。我发现的快速修复方法目前仍然有效,但它可能无法满足日常使用的严格要求。又是一个伟大的解决方案!
- (void) quantityDown:(id)sender{
   MyButton *btn  = (MyButton *)sender;
   //You get the object directly
   btn.obj;
}
UIButton *b = [UIButton buttonWithType:UIButtonTypeContactAdd];
b.tag = indexPath.row;
[b addTarget:self action:@selector(quantityDown:) forControlEvents:UIControlEventTouchUpInside];
 - (void)quantityDown:(id)sender  
    {    
       NSLog(@"%d", sender.tag);  
    }