【问题标题】:Nested collectionView in a TableViewTableView 中的嵌套 collectionView
【发布时间】:2018-10-23 05:35:52
【问题描述】:

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

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

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

我尝试了几次以尊重 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?

非常感谢您的帮助!

【问题讨论】:

    标签: ios swift uitableview uicollectionview


    【解决方案1】:

    这很简单。每个视图及其子类都有一个属性tag。您必须有一个IBOutlet 或对位于TableViewCell 中的CollectionView 的简单引用。当您将TableViewCell 出列时,只需将CollectionView 的标签设置为等于tableViewCellindexPath.row,如下所示:

    tableViewCell.collectionView.tag = indexPath.row
    

    然后在UICollectionViewDataSourceUICollectionViewDelegate 方法中,您可能会发现它是哪个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
    }
    

    P.S:没有必要在那种程度上尊重 MVC。您可以从 TableViewCell 管理您的 CollectionView。看看这个example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      相关资源
      最近更新 更多