在uitableviewcell中获取一个按钮,与didSelect Cell一样运行

时间:2013-07-04 18:16:29

标签: ios ios5 uitableview uibutton

我在单元格中有一个带有UIButton的tableview。

我在didSelectRowAtIndexPath中创建了一些功能。我想要的是在用户点击按钮时运行相同的功能/方法。

如何让buttonPressed方法运行didSelectRowAtIndexPath?

如果我不能这样做,我可以将功能移到一个新方法,并同时调用这个新方法。但是,如何从按下按钮的方法获取单元格indexPath?

3 个答案:

答案 0 :(得分:0)

  1. 找到包含该按钮的UITableViewCell对象(必须是其容器视图之一,只需沿超级视图链向上)。
  2. 使用[UITableView indexPathForCell:]找到indexPath。

答案 1 :(得分:0)

-(IBAction)playButtonPressed:(id)sender {
    NSLog(@"button pressed");
    UIButton *button = (UIButton *)sender;
    UITableViewCell *cell = (UITableViewCell *)button.superview.superview;
    UITableView *curTableView = (UITableView *)cell.superview;
    NSIndexPath *indexPath = [curTableView indexPathForCell:cell];

    [self didSelectRowOrButtonAtIndexPath:indexPath];
}

我创建了一个新方法didSelectRowOrButtonAtIndexPath,并从buttonPressed和didSelectRowAtIndexPath调用它,并传入索引路径以在我的方法中使用。

答案 2 :(得分:0)

cellForRowAtIndexPath中,将indexPath.row分配给按钮tag(假设您只需要行 - 我的想法是以某种方式将indexPath附加到按钮, tag只是一种方法。)

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {

    // Init / Reuse the cell ...

    cell.button.tag = indexPath.row;

    return cell;
}

-(void)buttonPressed:(UIButton*)button {
    [self method:button.tag];
}