如何在不使用Storyboard或IB的情况下从嵌入式集合视图的单元格导航到另一个视图控制器?

问题描述 投票:0回答:1

关于app(UICollectionView中的UICollectionView):

  • TabBarController是应用程序窗口的根视图控制器
  • TabBarController包含3个导航控制器。
  • 第一个导航控制器将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)
}
ios swift uinavigationcontroller
1个回答
0
投票

从单元推送视图控制器绝不是一个好主意。您需要将点击事件从ItemCell传播到HomeViewControlller。 在你的CategoryCollectionView中定义了一个类型为闭包的公共属性。

var onDidSelectItem: ((IndexPath) -> ())?

现在在CategoryCollectionViewdidSelectItem,像这样打电话给关闭。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        self.onDidSelectItem?(indexPath)
}

在你的HomeViewControlllercellForRow中,收到回调。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    categoryCollectionView.onDidSelectItem = {(indexPath) in
       //item at indexPath clicked, do whatever you want to do with it.
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.