iOS – 传递参数:@selector()

我以编程方式向UITableViewCell添加button。 按下button时要运行的方法是- (void) quantityDown:(id)sender rowNumber:(int)rowNum ,其中rowNum是button出现的行。

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

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

但不pipe我尝试什么,我都不能将行号传入方法。 我假定代码的相关部分看起来像

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

但这并不能解决问题。 我见过其他的东西

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

 action:@selector(quantityDown:rowNumber:)withObject:@"first" withObject:@"Second" 

但是都没有工作。 我不需要传递第一个参数,只是行号。 我也试着定义方法像- (void) quantityDown:(int)rowNum然后写入select器,如:

 action:@selector(quantityDown:indexPath.row) 

但是这也行不通。

思考?

提前致谢。

你为什么不做一个Custom UIButton class并具有该属性的对象?

见下文。

“MyButton.h”

 @interface MyButton : UIButton @property(nonatomic, strong)MyClass *obj; @end 

“MyButton.m”

 #import "MyButton.h" @implementation MyButton - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // Initialization code } return self; } @end 

现在将MyButton class分配给单元格中的实际button,或者初始化自定义button,而不是普通的UIButton class并直接指定对象。

并在您的IBAction sender=MyButton

 - (void) quantityDown:(id)sender{ MyButton *btn = (MyButton *)sender; //You get the object directly btn.obj; } 

这样做,您可以实际访问许多您想要的属性。 而且在其他实现中也是有用的。

希望能帮助到你。

button可以只携带一个input,所以要保持你的发件人和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); } 

希望这将有助于…

将每个button标签设置为indexPath.row 。 然后声明这个函数:

 - (void)quantityDown:(id)sender 

在这个方法中做到这一点:

 UIButton *btn = (UIButton *)sender; 

像这样添加目标:

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

btn.tag你可以得到行号。 希望这可以帮助。 🙂