当点击单元格内的图像时如何获取indexPath [英] How to get indexPath when image inside cell tapped
问题描述
我想实现一个功能,如果在 tableviewCell 中点击 profileImage,则转至 detailView.我添加了 tapGesture 但我仍然无法弄清楚如何让 indexPath 传递数据.我试过这样,但应用程序会崩溃.
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!
推荐答案
1: 在 cellForRowAtIndexpath 方法中设置 ImageView 的标签,标签将等于 indexPath.row
1: set tag of ImageView in cellForRowAtIndexpath method , tag will be equal to indexPath.row
imgView.tag = indexPath.row
2: 添加目标到附加在 imageView 上的 tapGuestureRecognizer
2: add a target to tapGuestureRecognizer attached on imageView
3: 在该方法中获取 imageView 的标签
3: get tag of imageView in that method
let imgView = sender as! UIImageView
let tag = imgView.tag
4:相应地获取数据,并推送
4: get data accordingly ,and push
let next = self.storyBoard.instatiateViewController(WithIdentifer:"detailVC")
next.data = datas[tag]
self.navigationController.pushViewController(next)
这篇关于当点击单元格内的图像时如何获取indexPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!