Search code examples
swiftuitableviewnsindexpath

How to get indexPath when image inside cell tapped


I would like to implement feature that if profileImage tapped in tableviewCell, segue to detailView. I add tapGesture but I still can't figure out how to get indexPath to pass data. I tried like this but app will crash.

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        if segue.identifier == "detailSegue" {
            let next: DetailViewController = segue.destination as! DetailViewController
          // pattern1
 let indexPath = tableView.indexPath(for: sender as! CustomTableViewCell)
         // pattern2
        let indexPath = tableView.indexPathForSelectedRow! as NSIndexPath

            next.data = datas[indexPath.row]
        }
    }

How can I fix this? Thank you in advance!


Solution

  • 1: set tag of ImageView in cellForRowAtIndexpath method , tag will be equal to indexPath.row

    imgView.tag = indexPath.row
    

    2: add a target to tapGuestureRecognizer attached on imageView

    3: get tag of imageView in that method

    let imgView = sender as! UIImageView
    let tag = imgView.tag
    

    4: get data accordingly ,and push

    let next = self.storyBoard.instatiateViewController(WithIdentifer:"detailVC") 
    next.data = datas[tag]
    self.navigationController.pushViewController(next)