我正在以编程方式向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)但这也不起作用。
有什么想法?
提前谢谢。
发布于 2014-04-03 12:05:33
为什么不创建一个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分配给单元格中的实际按钮,或者初始化自定义按钮而不是普通的UIButton class并直接分配对象。
在sender=MyButton所在的IBAction中
- (void) quantityDown:(id)sender{
MyButton *btn = (MyButton *)sender;
//You get the object directly
btn.obj;
}通过这种方式,您实际上可以轻松地访问任意多个属性。它在其他实现中也很有用。
希望能有所帮助。
发布于 2014-04-03 13:25:06
按钮只能携带一个输入,因此请保持发送者和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);
}希望这能有所帮助..。
发布于 2014-04-03 11:35:48
将每个按钮标记设置为indexPath.row。然后只需声明函数:
- (void)quantityDown:(id)sender在该方法中,执行以下操作:
UIButton *btn = (UIButton *)sender;像这样添加目标:
[buttonDown addTarget:self action:@selector(quantityDown:) forControlEvents:UIControlEventTouchUpInside];您可以从btn.tag获取行号。希望这能有所帮助。:)
https://stackoverflow.com/questions/22827259
复制相似问题