Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
863 views
in Technique[技术] by (71.8m points)

swift - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you add UITapGestureRecognizer to an UIImageView then don't forget to set isUserInteractionEnabled property to true.

Create a variable to store selected indexPath.row

var selectedCell:Int!

In cellForRow method add gesture to the image view.

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapBtnAction(_:)))
cell.imageView.tag = indexPath.row
cell.imageView.addGestureRecognizer(tapGesture)

In target method perform segue

func tapBtnAction(_ sender: UITapGestureRecognizer) {
    print("(sender.view.tag) Tapped")
    self.selectedCell = sender.view.tag
    self.performSegueWithIdentifier("detailSegue", sender: self)
}

In prepareforsegue method get data from the array.

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

   if segue.identifier == "detailSegue" {
      let next: DetailViewController = segue.destination as! DetailViewController
       next.data = datas[self.selectedCell]
   }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...