uitableViewCell的indexPath

时间:2013-10-18 00:10:18

标签: ios objective-c cocoa-touch uitableview

我有一个自定义方法来检测单元格图像上的点按。我还想找到图像的相关单元格的索引路径,并在函数中使用它。这是我正在使用的:

的cellForRowAtIndexPath:

UITapGestureRecognizer *tapped = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cellImageTapped:)];
tapped.numberOfTapsRequired = 1;
[cell.imageView addGestureRecognizer:tapped];

方法我试图获取索引路径:

  -(void)cellImageTapped:(id)sender {
   if(videoArray.count > 0){
       Video *currentVideo = [videoArray objectAtIndex:INDEX_PATH_OF_CELL_IMAGE];
     //do some stuff          
  }
}

我不知道如何传递索引路径。有什么想法吗?

5 个答案:

答案 0 :(得分:6)

简单方法:

  • 获取触摸点

  • 然后在点

  • 获取单元格的索引路径

代码是:

-(void)cellImageTapped:(id)sender {
    UITapGestureRecognizer *tap = (UITapGestureRecognizer *)sender;
    CGPoint point = [tap locationInView:theTableView];

    NSIndexPath *theIndexPath = [theTableView indexPathForRowAtPoint:point];

    if(videoArray.count > 0){
        Video *currentVideo = [videoArray objectAtIndex:theIndexPath];
        //do some stuff
    }
}

答案 1 :(得分:4)

我建议这种方式来获取具有自定义子视图的单元格的indexPath - (与iOS 7以及所有以前的版本兼容

- (void)cellImageTapped:(UIGestureRecognizer *)gestureRecognizer
{
    UIView *parentCell = gestureRecognizer.view.superview;

    while (![parentCell isKindOfClass:[UITableViewCell class]]) {   // iOS 7 onwards the table cell hierachy has changed.
        parentCell = parentCell.superview;
    }

    UIView *parentView = parentCell.superview;

    while (![parentView isKindOfClass:[UITableView class]]) {   // iOS 7 onwards the table cell hierachy has changed.
        parentView = parentView.superview;
    }


    UITableView *tableView = (UITableView *)parentView;
    NSIndexPath *indexPath = [tableView indexPathForCell:(UITableViewCell *)parentCell];

    NSLog(@"indexPath = %@", indexPath);
}

答案 2 :(得分:1)

UIImageView的{​​{1}}方法中为UITableViewDataSource添加标记。

tableView:cellForRowAtIndexPath:

答案 3 :(得分:1)

使用委托方法didSelectRowAtIndexPath:method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self cellImageTapped:indexPath];
}

然后你可以将索引传递给函数,即

-(void)cellImageTapped:(NSIndexPath *)indexPath
{
    Video *currentVideo = [videoArray objectAtIndex:indexPath.row];
}

答案 4 :(得分:1)

我最终使用了发送者的视图标记。希望这会帮助某人,因为我浪费了一个小时才找到答案。

-(void)cellImageTapped:(id)sender {

UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;

            if(videoArray.count > 0){
                NSInteger datIndex = gesture.view.tag;
                Video *currentVideo = [videoArray objectAtIndex:datIndex];
            }

}