小编典典

当单元格内的图像被点击时如何获取indexPath

swift

我想实现的功能是,如果profileImage在tableviewCell中点击,则选择到detailView。我添加了tapGesture,但是我仍然不知道如何获取indexPath来传递数据。我试图这样,但应用程序将崩溃。

    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]
        }
    }

我怎样才能解决这个问题?先感谢您!


阅读 278

收藏
2020-07-07

共1个答案

小编典典

1:在cellForRowAtIndexpath方法中设置ImageView的标签,该标签将等于indexPath.row

imgView.tag = indexPath.row

2:将目标添加到附加在imageView上的tapGuestureRecognizer

3:在该方法中获取imageView的标签

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

4:据此获取数据并推送

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