2

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

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          
  }
}

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

4

5 回答 5

5

简单的方法:

  • 获得接触点

  • 然后在点处获取单元格的索引路径

代码是:

-(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
    }
}
于 2013-10-18T03:21:09.623 回答
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);
}
于 2013-10-18T02:55:53.213 回答
1

我最终使用了发件人的视图标签。希望这会对某人有所帮助,因为我浪费了一个小时来寻找答案。

-(void)cellImageTapped:(id)sender {

UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;

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

}
于 2013-10-18T01:26:09.360 回答
1

UIImageView在你UITableViewDataSourcetableView:cellForRowAtIndexPath:方法中添加一个标签。

cell.imageView.tag = indexPath.row;
于 2013-10-18T00:24:30.453 回答
1

使用委托方法 didSelectRowAtIndexPath: 方法

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

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

-(void)cellImageTapped:(NSIndexPath *)indexPath
{
    Video *currentVideo = [videoArray objectAtIndex:indexPath.row];
}
于 2013-10-18T00:24:37.203 回答