2

I've image in cell, I've added gesture recogniser for this image. After deleting a cell from table the indexPath of the cells below the deleted cell is incorrect which cause app to crash.

How do I get indexPath from gesture recogniser when image inside cell is tapped?

I've searched a lot but can't find a working solution. Below is the code which I've right now. This code returns incorrect row.

P.S. Please don't suggest adding button on top of Image as I'm already aware of this.

@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)")
}
Raymond
  • 1,108
  • 13
  • 32

2 Answers2

3

Well, you need to change your code little bit instead of gesture.view you need to find location in your 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)")

}

and if problem still persists, you can give tag to imageView like this

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
umer farooqi
  • 552
  • 2
  • 8
0
@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)")
}
Sharad Paghadal
  • 2,089
  • 15
  • 29