关于app(UICollectionView中的UICollectionView):
HomeViewController
作为根视图控制器HomeViewController
包含CategoryCollectionView
CategoryCollectionView
的每个细胞内部存在一个ItemCollectionView
ItemCollectionView
包含许多ItemCell
目标:当用户点击ItemCell
时,应用程序应导航到另一个视图控制器ItemViewController。我正在使用代码完全开发这个应用程序。所以我想在没有Storyboard segues或IB的情况下做到这一点。到目前为止我还没弄清楚。如果你能指出我正确的方向,那就太好了。谢谢。
我尝试了以下,但他们没有工作:
第一种方法:从CategoryCollectionView
的单元格中访问窗口的根视图控制器
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let currentNavCon = self.window?.rootViewController!.navigationController
currentNavCon?.pushViewController(ItemViewController(), animated: true)
}
第二种方法:我在itemCellClicked
中定义了一个函数HomeViewController
,并在didSelectItemAt
的单元格的CategoryCollectionView
中调用它。
func itemCellClicked(_ sender: CatalogViewCategoryCell, _ position: Int) {
let itemViewController = ItemViewController()
navigationController?.pushViewController(itemViewController, animated: true)
}
而且,在细胞内:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
HomeViewController().itemCellClicked(self, indexPath.item)
}
从单元推送视图控制器绝不是一个好主意。您需要将点击事件从ItemCell
传播到HomeViewControlller
。
在你的CategoryCollectionView
中定义了一个类型为闭包的公共属性。
var onDidSelectItem: ((IndexPath) -> ())?
现在在CategoryCollectionView
的didSelectItem
,像这样打电话给关闭。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.onDidSelectItem?(indexPath)
}
在你的HomeViewControlller
的cellForRow
中,收到回调。
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
categoryCollectionView.onDidSelectItem = {(indexPath) in
//item at indexPath clicked, do whatever you want to do with it.
}
}