ios - 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?
非常感谢您的帮助!
解决方案
这很简单。每个视图及其子类都有一个属性tag
。您必须IBOutlet
对CollectionView
位于TableViewCell
. 当您出列时,TableViewCell
只需将您的标签设置为您的标签,CollectionView
如下indexPath.row
所示tableViewCell
:
tableViewCell.collectionView.tag = indexPath.row
然后在UICollectionViewDataSource
orUICollectionViewDelegate
方法中,您可能会发现它是哪个 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。看看这个例子。
推荐阅读
- php - pi的不同值?
- python - 将 HTML 标记删除应用于 Pandas 列
- wordpress - 如何在 Wordpress 中设置自己的分类顺序?
- angular - 如何在angular2 +中的选择属性中显示多个iframe作为值
- python - Odoo 创建自动报告并使用电子邮件模板将其发送给特定用户
- javascript - 在fancybox中显示地图
- azure-devops - ServiceFabric 部署。修改托管代理上的主机
- c - 我需要制作一个目标文件,还是只是最终的可执行文件?
- java - Mac OSX 上的 Java 10 辅助启动器的替代方案是什么?
- javascript - php中的jquery ajax停止重新加载页面