![](/img/trans.png)
[英]Swift: How to get the table row cell (indexPath) and load it from the data model in detail view controller?
[英]How to get indexPath from image gesture in table view's cell
我在單元格中有圖像,我為此圖像添加了手勢識別器。 從表中刪除單元格后,已刪除單元格下方單元格的 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)")
}
@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.