首页 > 解决方案 > 如何从表格视图单元格中的图像手势获取 indexPath

问题描述

我在单元格中有图像,我为此图像添加了手势识别器。从表中删除单元格后,已删除单元格下方单元格的 indexPath 不正确,导致应用程序崩溃。

当点击单元格内的图像时,如何从手势识别器获取 indexPath?

我进行了很多搜索,但找不到有效的解决方案。下面是我现在的代码。此代码返回不正确的行。

PS请不要建议在图像顶部添加按钮,因为我已经知道这一点。

@objc func imageTapped(_ gesture:UITapGestureRecognizer){

    guard let indexPath = myTableView.indexPathForRow(at: gesture.location(in: gesture.view)) else {
        print("Error: indexPath)")
        return
    }

    print("indexPath.row: \(indexPath.row)")
}

标签: iosswiftuitableviewuigesturerecognizer

解决方案


好吧,您需要稍微更改代码而不是gesture.view,您需要在tableView中找到位置

@objc func imageTapped(_ gesture:UITapGestureRecognizer){

guard let indexPath = myTableView.indexPathForRow(at: gesture.location(in: self.tableView)) else {
    print("Error: indexPath)")
    return
}

print("indexPath.row: \(indexPath.row)")

}

如果问题仍然存在,您可以像这样为 imageView 提供标签

imageview.tag = indexPath.row //place it in cellForRow

//place below lines in gesture handler
guard let view = sender.view else {return}
let indexPath = IndexPath(row:view.tag, section: 0) //only works if section remains same/ unique

推荐阅读