自定义UITableViewCell与按钮
问题描述:
我subclassed UITableViewCell并添加一个按钮。当按钮被触摸时,我该如何回应事件?我还需要知道按下哪个索引路径。自定义UITableViewCell与按钮
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CustomTableCell";
CustomTableCell *cell = (CustomTableCell *)
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *topLevelObjects = [[NSBundle mainBundle]
loadNibNamed:@"CustomTableCell"
owner:nil options:nil];
for (id currentObjects in topLevelObjects){
if ([currentObjects isKindOfClass:[StatusTableCell class]]){
cell = (StatusTableCell *) currentObjects;
break;
}
}
}
cell.customButton.tag = indexPath.row;
return cell;
}
答
如果您已通过UITableViewCell子类中的代码添加了UIButton,则可以使用以下代码为其添加操作。
//In UITableViewCell subclass
[customButton addTarget:self
action:@selector(aMethod:)
forControlEvents:UIControlEventTouchDown];
然后你已经写的代码通过设置访问行号,
cell.customButton.tag = indexPath.row;
你可以在该amethod方法标签值并访问像下面的indexPath.row值,
//In UITableViewCell subclass
-(IBAction)aMethod:(UIButton*)button
{
NSLog(@"indexPath.row value : %d", button.tag);
}
+0
这是正确的方法。假设它只有1个部分,但... – HelmiB
答
您可以在CustomTableCell笔尖和功能分配IBAction为做这样的事情:
- (IBAction) btnDoSomethingPressed:(id)sender {
NSIndexPath *indexPath = [yourTableView indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
//Use indexPath (or indexPath.row) like you would in a UITableViewDelegate method
}
这假定yourTableView
是分配给您的表的实例变量。
[参考此链接] [1] [1]:http://*.com/questions/869421/using-a-custom-image-for-a-uitableviewcells-accessoryview-并有回应 – HelmiB