首页 > 解决方案 > TableView 中的嵌套 collectionView

问题描述

一段时间以来,我已经成功地将集合视图嵌套到 tableview 中。

我仍然不知道该怎么做,是在尊重 MVC 模式的同时做到这一点吗?

现在,我声明了我的 tableview 及其单元格,在单元格(collectionView 所在的位置)中,我附加了我的 collectionView(每个单元格有 1 个)并进行数据映射。它可以工作,但它是意大利面条代码,我的视图就像一个控制器。

我尝试了几次以尊重 MVC 模式。我可以让我的控制器同时控制我的 tableview 和我的收藏。我努力的地方是告诉我的集合视图委托它应该选择哪些数据,因为我作为参考的所有数据是 indexPath(collectionView 的),而不是特定 collectionView 位于哪个 tableView 中。

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
    return cell
}

委托只给我单元格的 indexPath,而不是它的 collectionView。举一个具体的例子——让我们假设我的表格视图单元格表示消息,并且每条消息都有一个控制反应的 collectionView(如 Discord)。如何告诉我的 collectionView 委托它链接到哪个 Message?

非常感谢您的帮助!

标签: iosswiftuitableviewuicollectionview

解决方案


这很简单。每个视图及其子类都有一个属性tag。您必须IBOutletCollectionView位于TableViewCell. 当您出列时,TableViewCell只需将您的标签设置为您的标签,CollectionView如下indexPath.row所示tableViewCell

tableViewCell.collectionView.tag = indexPath.row

然后在UICollectionViewDataSourceorUICollectionViewDelegate方法中,您可能会发现它是哪个 collectionView,换句话说,这个 collectionView 位于哪个 tableViewCell 中。这是一个示例:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
    let dataObject = dataSourceArray[indexPath.row] as! YourDataModelObject

    // Here you may set any property of the collectionView cell
    return cell
}

PS:没必要那么尊重MVC。您可以从 TableViewCell 管理您的 CollectionView。看看这个例子


推荐阅读