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

Bir*_*rel 3 methods action objective-c selector ios

我正在以编程方式向UITableViewCell添加一个按钮.当按下按钮是要运行的方法- (void) quantityDown:(id)sender rowNumber:(int)rowNum,其中rowNum是在按钮出现在该行.

将目标添加到按钮时,Xcode会自动填充以下内容:

[buttonDown addTarget:self action:@selector(quantityDown:rowNumber:) forControlEvents:UIControlEventTouchUpInside];
Run Code Online (Sandbox Code Playgroud)

但无论我尝试什么,我都无法将行号传递给方法.我假设相关的代码部分看起来像

action:@selector(quantityDown:rowNumber:indexPath.row)
Run Code Online (Sandbox Code Playgroud)

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

action:@selector(quantityDown:)rowNumber:indexPath.row
Run Code Online (Sandbox Code Playgroud)

action:@selector(quantityDown:rowNumber:)withObject:@"first" withObject:@"Second"
Run Code Online (Sandbox Code Playgroud)

但是没有工作.我不需要传递第一个参数,只需要传递行号.我也尝试过定义类似的方法- (void) quantityDown:(int)rowNum然后编写选择器,如:

action:@selector(quantityDown:indexPath.row)
Run Code Online (Sandbox Code Playgroud)

但这也行不通.

思考?

提前致谢.

iph*_*nic 8

你为什么不Custom UIButton class把这个物品作为财产?

见下文.

"MyButton.h"

@interface MyButton : UIButton
@property(nonatomic, strong)MyClass *obj;
@end
Run Code Online (Sandbox Code Playgroud)

"MyButton.m"

#import "MyButton.h"

@implementation MyButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

@end
Run Code Online (Sandbox Code Playgroud)

现在分配MyButton class到单元格中的实际按钮/或初始化自定义按钮而不是正常按钮UIButton class并直接分配对象.

而在你的IBAction地方sender=MyButton

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

通过这种方式,您可以轻松访问所需的多个属性.它在其他实现中也很有用.

希望能帮助到你.