将UIButton touch事件发送到didSelectRowAtIndexPath

时间:2011-08-18 11:06:28

标签: iphone uitableview uibutton

我将UIButton添加到UITableViewCell

为了减少代码冗余,我想触摸UIButton的事件通过单元格 - 所以它最终在:

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
你能告诉我怎么样?

2 个答案:

答案 0 :(得分:8)

在按钮的操作方法中,您可以从表视图中确定行的索引路径,并将其传递给委托方法:

- (IBAction)buttonClicked:(UIButton *)button
{
    CGPoint point = [button center];
    UITableView *table = [self tableView];
    NSIndexPath *indexPath = [table indexPathForRowAtPoint:point];
    [[table delegate] tableView:table didSelectRowAtIndexPath:indexPath];
}

答案 1 :(得分:4)

这是一个坏主意。相反,你应该从didSelectRowAtIndexPath:&中调用相同的函数。按钮的动作方法&将您的公共代码放在该函数中。像 -

这样的东西
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//fetch the cell corresponding to this index path
MyCustomCell* cell = (MyCustomCell*)[self cellForRowAtIndexPath:indexPath] ;
[cell foo] ; 


}

-(void) buttonClicked:(id)sender //In your custom cell class
{
    [self foo];
}

HTH,

阿克沙伊