从嵌入在tableview单元格中的uicollectionview执行segue选择?

目前,我们有一个嵌入在tableview单元格中的uicollectionview。 当选择集合视图单元格时,它假设启动push segue到另一个视图控制器。 问题是没有选项来执行单元格上的segue。 有办法解决吗? 这是单元格:

class CastCell : UITableViewCell { var castPhotosArray: [CastData] = [] let extraImageReuseIdentifier = "castCollectCell" let detailToPeopleSegueIdentifier = "detailToPeopleSegue" var castID: NSNumber? @IBOutlet weak var castCollectiontView: UICollectionView! override func awakeFromNib() { castCollectiontView.delegate = self castCollectiontView.dataSource = self } } extension CastCell: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return castPhotosArray.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = castCollectiontView.dequeueReusableCell(withReuseIdentifier: extraImageReuseIdentifier, for: indexPath) as! CastCollectionViewCell cell.actorName.text = castPhotosArray[indexPath.row].name return cell } } extension CastCell: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.castID = castPhotosArray[indexPath.row].id performSegue(withIdentifier: detailToPeopleSegueIdentifier, sender: self) //Use of unresolved identifier 'performSegue' error } } extension CastCell { func prepare(for segue: UIStoryboardSegue, sender: Any?) { let peopleVC = segue.destination as! PeopleDetailViewController peopleVC.id = self.castID } } 

问题是没有选项来执行单元格上的segue

没有“细胞上的细胞”这样的东西。 segue是从一个视图控制器到另一个视图控制器。 performSegue是一个UIViewController方法。 所以你不能在你的CastCell类中说performSegue ,因为这意味着self.performSegue ,而self是一个UITableViewCell – 它没有performSegue方法。

因此,解决方案是让自己引用控制此场景的视图控制器,并在其上调用performSegue

在像你这样的情况下,我喜欢这种参考的方式是走在响应链上。 从而:

 var r : UIResponder! = self repeat { r = r.next } while !(r is UIViewController) (r as! UIViewController).performSegue( withIdentifier: detailToPeopleSegueIdentifier, sender: self) 

1:一个干净的方法是在UITableViewCell类中创建一个delegate protocol ,并将UIViewController设置为响应者。

2:一旦UICollectionViewCell被点击,处理UITableViewCell内的点击并通过UICollectionViewCell将点击转发给你的UIViewController responder

3:在你的UIViewController ,你可以在点击时动作并从那里执行/推送/呈现你想要的任何东西。

您希望您的UIViewController知道发生了什么,而不是从不应该处理这些方法的“不可见”子类调用push / presents。

这样,您还可以将delegate protocol用于将来需要转发到UIViewController其他方法,如果需要,干净且简单。