6

我有一个包含两个动作的表格视图,第一个是我使用委托 didSelectRowAtIndexPath,第二个是我想在我的单元格上的按钮上使用一个动作来做其他事情。我的问题是我没有成功获得 indexpath ?这样做的最佳做法是什么。

4

5 回答 5

9

如果您已将按钮添加到单元格中,

[cell.contentView addSubview:button];

然后,您可以获得索引路径,

- (void)onButtonTapped:(UIButton *)button {

    UITableViewCell *cell = (UITableViewCell *)button.superview.superview;
    NSIndexPath *indexPath = [tableView indexPathForCell:cell];
    // Go ahead
}
于 2011-09-17T04:27:40.720 回答
2

我正在使用这个解决方案——使用点获取单元格的索引路径

CGPoint center= [sender center];
CGPoint rootViewPoint = [[sender superview] convertPoint:center toView:_tableView1];
NSIndexPath *indexPath = [_tableView1 indexPathForRowAtPoint:rootViewPoint];
NSLog(@"%@",indexPath);

它的工作完美

于 2014-11-21T08:20:55.747 回答
1

这是自定义按钮的完整代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    CustomCellFilter *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {cell = [[CustomCellFilter alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];}

    //configure your cell here
    cell.titleLabel.text = @"some title";

    //add button
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
    resetButton.frame = CGRectMake(40, 10, 18, 18);
    [resetButton addTarget:self action:@selector(onButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [resetButton setImage:[UIImage imageNamed:@"someimage.png"] forState:UIControlStateNormal];
    [cell.contentView addSubview:myButton];

    //afterwards return the cell
    return cell;

- (void)onButtonTapped:(UIButton *)button {

    UITableViewCell *cell = (UITableViewCell *)button.superview.superview;
    NSIndexPath *indexPath = [filterTable indexPathForCell:cell];
    NSLog(@"%@", indexPath);
    //use indexPath here...
}
于 2013-05-26T15:37:28.693 回答
0

如果您使用的是集合视图,您可以使用 Yogesh 方法,但将 indexPathForRowAtPoint 更改为 indexPathForItemAtPoint,如下所示:

CGPoint center= [sender center];
CGPoint rootViewPoint = [[sender superview] convertPoint:center toView:_tableView1];
NSIndexPath *indexPath = [_tableView1 indexPathForRowAtPoint:rootViewPoint];
NSLog(@"%@",indexPath);
于 2014-12-11T15:50:03.813 回答
-1

如果您的按钮被移动或 Apple 更改了附件视图的视图层次结构,则此方法会沿链向上查找 UITableViewCell:

- (void)tapAccessoryButton:(UIButton *)sender {
    UIView *parentView = sender.superview;

// the loop should take care of any changes in the view heirarchy, whether from
// changes we make or apple makes.
    while (![parentView.class isSubclassOfClass:UITableViewCell.class])
        parentView = parentView.superview;

    if ([parentView.class isSubclassOfClass:UITableViewCell.class]) {
        UITableViewCell *cell = (UITableViewCell *) parentView;
        NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
        [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
    }
}
于 2014-01-17T08:09:33.413 回答