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

3
我正在通过编程方式向UITableViewCell添加一个按钮。按下按钮时要运行的方法是- (void) quantityDown:(id)sender rowNumber:(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

并且

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

但是两种方法都不行。我不需要传递第一个参数,只需要传递行号。我也尝试过像这样定义方法:- (void) quantityDown:(int)rowNum,然后编写选择器:
action:@selector(quantityDown:indexPath.row)

但这也不起作用。

有什么想法?

提前致谢。


刚刚发现了这个帖子。会尝试一下。 - Birrel
没错,就是这样。我设置了 buttonDown.tag = indexPath.row,然后在方法中可以通过 UIButton *clicked = (UIButton *)sender; 访问它,然后将一个整数设置为 clicked.tag - Birrel
你不能在按钮点击事件中传递值。可能的方法是从按钮发送者中查找值,或在按钮点击时调用另一个方法。第一种方法是正确的。 - Vineesh TP
3个回答

8

为什么不创建一个自定义的UIButton类,并将其作为属性?

请参见下文。

"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类分配给您实际单元格中的按钮/或初始化自定义按钮而不是普通的UIButton类并直接分配对象。

在您的IBAction中,其中sender=MyButton

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

通过这种方式,您可以轻松访问所需的任意属性。而且它在其他实现中也很有用。

希望对您有所帮助。


是的,这是一个不错的解决方案。如果我需要的数据不仅仅是行号,这绝对是我选择的方式。我发现的临时解决方案现在正在运作,但它可能无法承受日常使用的严厉考验。再次感谢您提供了极佳的解决方案! - Birrel

4

按钮只能承载一个输入,因此请确保您的发送者和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);  
    }

希望这能有所帮助...


1
将每个按钮标签设置为indexPath.row。然后只需声明函数:
- (void)quantityDown:(id)sender

在该方法中,做这个:
UIButton *btn = (UIButton *)sender;

Add target like this:

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

btn.tag 中可以获取行号。希望这能帮到你。:)


是的。这就是我最终所做的,正如在原问题的评论中提到的那样。谢谢! - Birrel
不客气。是的,我现在看到了。可能我当时忙着打答案... :P - Rashad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接