【问题标题】:Can't Set Cell Size in Collection View inside Table View无法在表格视图内的集合视图中设置单元格大小
【发布时间】:2020-04-05 10:25:59
【问题描述】:

我有一个包含 4 个单元格的表格视图。在单元格 3 和 4 中,我有一个集合视图。我正在尝试在 Table View Cell 4 中设置集合视图,但是由于某种原因,我在界面构建器中选择的任何设备都是我尝试设置单元格大小时引用的设备。

在 TableViewController 我有这个代码:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout

        let totalSpace = flowLayout.sectionInset.left
            + flowLayout.sectionInset.right
            + (flowLayout.minimumLineSpacing * 3)

        let size = (collectionView.frame.width - totalSpace) / 4

        return CGSize(width: size, height: 166)
    }

将单元格划分为 4 个高度为 166 的单元格。但是,collection view.frame.width 没有引用实际的collection view,它引用的是界面生成器中的任何大小。

运行时,单元格大小取决于collectionview.frame.width,而那个值是错误的。

我已经在模拟器和设备上对此进行了测试。 不知道这里发生了什么?

更新:

我已经确定了导致问​​题的原因,但不确定如何解决。我正在根据内容高度大小设置集合视图的高度约束:

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let topCell = tableView.dequeueReusableCell(withIdentifier: "topCell", for: indexPath)

    switch indexPath.section {
    case 1:
        return secondCell
    case 2:
        let collectionViewCell = tableView.dequeueReusableCell(withIdentifier: "matchesCell", for: indexPath) as! collectionViewCellCustomClass

        let height = collectionViewCell.collectionView.collectionViewLayout.collectionViewContentSize.height
        collectionViewCell.heightConstant.constant = height
        self.view.setNeedsLayout()

        return collectionViewCell
    default:
        return topCell
    }
}

这告诉集合视图的高度是它的内容的高度。我在 tableView 单元格中设置了这个。但是,每当我删除这段代码时,单元格大小都可以正常工作吗?

【问题讨论】:

  • 添加结果截图
  • 你在你的collectionView上做过这个吗? stackoverflow.com/a/59188406/8201581
  • @YogeshPatel 不,这只是一个空的集合视图。我会添加截图。
  • 找到导致问题的原因,已更新。
  • 估计大小不属于您的收藏视图。

标签: swift uicollectionview


【解决方案1】:

问题已解决。真的很简单:

如果我设置:collectionView.reloadData() 它会修复它!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多