ios - 当点击单元格中的 UIImageView 时如何获取indexpath.row?

标签 ios swift uitableview uiimageview

swift: how to get the indexpath.row when a button in a cell is tapped?

此链接是点击按钮时的答案,如果无法回答我的问题,我将只使用按钮并将图像放在上面。我只是想知道是否可以通过点击 UIImageView 而不是按钮来实现这一点。我用 UIImageView 而不是 UIButton 尝试了确切的答案,但我得到了这个错误

"fatal error: unexpectedly found nil while unwrapping an Optional value".

cell.imagePosted 是一个 UIImageView

let tapGR = UITapGestureRecognizer(target: self,action:Selector("imageTapped:"))
cell.imagePosted.userInteractionEnabled = true
cell.imagePosted.addGestureRecognizer(tapGR);

func imageTapped(img: AnyObject)
{
    if let imgView = img as? UIImageView {

        if let superView = imgView.superview {

            if let cell = superView.superview as? CellCustom {

                indexPath2 = self.tableView.indexPathForCell(cell)

            }      
       }       
   }

   print(indexPath2.row)       
}

最佳答案

这可能对你有帮助,

UITapGestureRecognizer 添加到 UIImageView 您可以将 indexpath.row 存储在 UIImageView 的标记属性中,并在 UITapGestureRecognizer 事件

上访问该标记

例如( objective-C ):

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageTap:)];
    tap.cancelsTouchesInView = YES;
    tap.numberOfTapsRequired = 1;
    [cell.imageView addGestureRecognizer:tap];

    cell.imageView.tag = indexPath.row;

并获取indexpath.row

-(void)handleImageTap:(UITapGestureRecognizer *)gestureRecognizer{
    UIView* view = gestureRecognizer.view;
    CGPoint loc = [gestureRecognizer locationInView:view];
    NSInteger indexpath = [view hitTest:loc withEvent:nil].tag;
    NSLog(@"%ld",(long)indexpath);
}

关于ios - 当点击单元格中的 UIImageView 时如何获取indexpath.row?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35500137/

相关文章:

iOS 示例 Jpeg 颜色

swift - 如何达到 childByAutoId() 背后的值(value)

ios - 如何在不更改文本的 alpha 的情况下更改 TableViewCell 的 alpha?

cocoa-touch - UITableViewCell的accessoryView在可见 View 改变后消失

ios - UITableViewCell 内部的 UICollectionView

ios - 当你有多个按钮时,如何在 UITableView 中保持 UIButton 状态被选中?

ios - 调整大小时如何禁用子层的缩放?

ios - Firebase - 获取对存储在 childByAutoID 下的值的引用

ios - 我的 viewController 没有正确显示

ios - AVPlayer 无法快速播放 iPod-Library 歌曲项目