ios - 如何从表格视图单元格中的图像手势获取 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)")
}
解决方案
好吧,您需要稍微更改代码而不是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
推荐阅读
- r - 在 rmarkdown 的文本中打印 `ggplot2` 形状
- python - 读取多个数据文件时出现内存错误问题
- python-requests - Python 中的 XML 标记
- qt - SPI raspberry pi (master) & arduino due (slave)
- symfony - 如何在包含的模板之间共享变量(或者是否有替代方法)?
- json - django dict/queryset/list 到 json
- python - 如何使用 python 的正则表达式模式在换行符处提取文本?
- java - org.openqa.selenium.remote.UnreachableBrowserException:无法使用 Java 使用 Selenium 和 IE11 启动新会话错误
- python - 无法使用选择内标签内的href触发烧瓶视图功能
- python - 如何从远程服务器接收 UDP 数据包