【问题标题】:UICollectionView inside TableView not populating cells?TableView 中的 UICollectionView 不填充单元格?
【发布时间】:2015-07-23 01:17:53
【问题描述】:

我有一个 tableView,其中的行需要水平流动的 collectionView。

我的 tableView 单元格中有一个 collectionView,然后我像这样实例化它们:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("MyTableViewCell", forIndexPath: indexPath) as! MyTableViewCell
    let nibName = UINib(nibName: "CollectionCell", bundle: nil)
    cell.collectionView.registerNib(nibName, forCellWithReuseIdentifier: "CollectionCell")
    cell.collectionView.dataSource = self
    cell.collectionView.delegate = self

    return cell
}

我正在尝试使用自动高度表视图行,我认为这可能会导致问题。如何将 UITableViewAutomaticDimension 与内部集合视图一起使用?

【问题讨论】:

  • 您可能需要在设置好委托和数据源后调用reloadData
  • @Qazi 在 cellForRowAtIndexPath 中这样做了,没有效果。
  • 对不起,我没说清楚,所以你在集合视图上调用reloadData,而不是在 TableView 上?
  • @Qazi 是的。在集合视图上。

标签: ios swift uitableview uicollectionview


【解决方案1】:

这是在objective-c中,但对我有用:

我。在自定义单元格的 .m 文件中注册 UICollectionViewCell nib,并指定布局详细信息(大小、间距等)。

二。在持有 tableView 的 VC 中,其 .m 在cellForRowAtIndexPath中执行以下操作

 MyTableViewCell *cell = (MyTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"MyTableViewCellId" forIndexPath:indexPath];

    cell.collectionView.delegate = self;
    cell.collectionView.dataSource = self;
    cell.collectionView.tag = indexPath.row;

    [cell.collectionView reloadData];

三。您可以在委托方法中使用UICollectionView 的标签来填充正确的信息

这有帮助。

【讨论】:

  • 我正在尝试使用自动高度表视图行,我认为这可能会导致问题。如何将 UITableViewAutomaticDimension 与内部集合视图一起使用?
  • 这确实有效。你需要确保布局中的itemSize设置好了,并且当tableview设置为AutomaticDimension时,包含collection view的cell的autolayout约束指定了一个高度
  • @StefanKendall 你是绝对正确的,抱歉忘了包括那个..刚刚添加了答案
【解决方案2】:

尝试添加 - cell.setTranslatesAutoresizingMaskIntoConstraints(false) - 见下文

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell: MyTableViewCell = tableView.dequeueReusableCellWithIdentifier("MyTableViewCell", forIndexPath: indexPath) as! MyTableViewCell
    let nibName = UINib(nibName: "CollectionCell", bundle: nil)
    cell.collectionView.registerNib(nibName, forCellWithReuseIdentifier: "CollectionCell")
    cell.collectionView.dataSource = self
    cell.collectionView.delegate = self
    cell.setTranslatesAutoresizingMaskIntoConstraints(false)

    return cell
}

有关更多信息,请参阅https://www.captechconsulting.com/blogs/ios-8-tutorial-series-auto-sizing-table-cells

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 2016-01-15
    • 2014-04-27
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多