iOS-在操作中传递参数:@selector() [英] iOS - passing arguments in action:@selector()
问题描述
我正在以编程方式向UITableViewCell添加一个按钮.按下按钮时要运行的方法是- (void) quantityDown:(id)sender rowNumber:(int)rowNum
,其中rowNum
是按钮出现的行.
I'm adding a button to a UITableViewCell programmatically. The method to be run when the button is pressed is - (void) quantityDown:(id)sender rowNumber:(int)rowNum
, where rowNum
is the row that the button appears in.
将目标添加到按钮时,Xcode会自动完成以下操作:
When adding the target to the button, Xcode autocompletes the following:
[buttonDown addTarget:self action:@selector(quantityDown:rowNumber:) forControlEvents:UIControlEventTouchUpInside];
但是无论我如何尝试,都无法将行号传递给方法.我认为代码的相关部分看起来像
But no matter what I try, I cannot pass the row number into the method. I assumed the pertinent portion of code would look like
action:@selector(quantityDown:rowNumber:indexPath.row)
但这并不能解决问题.我看过其他东西,例如
but that doesn't do the trick. I've seen other stuff like
action:@selector(quantityDown:)rowNumber:indexPath.row
和
action:@selector(quantityDown:rowNumber:)withObject:@"first" withObject:@"Second"
但是都行不通.我不需要传递第一个参数,只需传递行号.我也尝试过定义- (void) quantityDown:(int)rowNum
之类的方法,然后像这样编写选择器:
But neither work. I don't need to pass a first argument, just the row number. I've also tried defining the method like - (void) quantityDown:(int)rowNum
and then writing the selector like:
action:@selector(quantityDown:indexPath.row)
但这也不起作用.
有想法吗?
谢谢.
推荐答案
为什么不创建Custom UIButton class
并将对象作为属性?
Why don't you make a Custom UIButton class
and have the object as property?
请参阅下文.
"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
分配给单元格/中的实际按钮,或者初始化自定义按钮,而不是普通的UIButton class
并直接分配对象.
Now assign MyButton class
to your actual button in the cell/ or initialize the custom button instead of normal UIButton class
and assign the object directly.
在您的IBAction
中,其中sender=MyButton
- (void) quantityDown:(id)sender{
MyButton *btn = (MyButton *)sender;
//You get the object directly
btn.obj;
}
通过这种方式,您实际上可以轻松地访问任意数量的属性.并且它在其他实现中也很有用.
Doing it this way you can actually access as many properties you want easily. And its useful in other implementations too.
希望有帮助.
这篇关于iOS-在操作中传递参数:@selector()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!