如何从 table 视图单元格中的图像手势获取 indexPath
How to get indexPath from image gesture in table view's cell
我在单元格中有图像,我为此图像添加了手势识别器。从 table 中删除一个单元格后,被删除单元格下方单元格的 indexPath 不正确,这会导致应用程序崩溃。
当点击单元格内的图像时,如何从手势识别器获取 indexPath?
我搜索了很多,但找不到可行的解决方案。下面是我现在的代码。此代码 returns 行不正确。
P.S。请不要建议在图像顶部添加按钮,因为我已经知道这一点。
@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)")
}
@objc func imageTapped(_ gesture:UITapGestureRecognizer){
guard let indexPath = myTableView.indexPathForRow(at: gesture.location(in: gesture.view)) else {
print("Error: indexPath)")
return
else{
path.indexPath(int x);
}
}
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
我在单元格中有图像,我为此图像添加了手势识别器。从 table 中删除一个单元格后,被删除单元格下方单元格的 indexPath 不正确,这会导致应用程序崩溃。
当点击单元格内的图像时,如何从手势识别器获取 indexPath?
我搜索了很多,但找不到可行的解决方案。下面是我现在的代码。此代码 returns 行不正确。
P.S。请不要建议在图像顶部添加按钮,因为我已经知道这一点。
@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)")
}
@objc func imageTapped(_ gesture:UITapGestureRecognizer){
guard let indexPath = myTableView.indexPathForRow(at: gesture.location(in: gesture.view)) else {
print("Error: indexPath)")
return
else{
path.indexPath(int x);
}
}
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