首页 > 解决方案 > 努力使集合视图高度适合内容

问题描述

我有一些特殊情况,无论我找到什么 StackOverflow 答案,它似乎都对我不起作用。我有一个包含动态单元格数量的集合视图(2-3 个单元格之间的任意位置)。但是,无论有多少单元格,此集合视图的高度将始终相同。

这是我设置单元格高度的逻辑:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // The cell's width and height, to be calculated
    var cellWidth: CGFloat = 0.0, cellHeight: CGFloat = 0.0
    
    // The number of cells to show, 2-3
    let count = numberOfCellsToShow
    
    // The width of the collection view
    let collectionViewWidth = collectionView.bounds.size.width
    
    // Calculate the maximum height for collection view (16:9 ratio)
    let collectionViewMaxHeight = collectionViewWidth / (16 / 9)
    
    // Get the width and height of each cell, with 4dp of spacing between cells
    if (count == 2) {
        cellWidth = (collectionViewWidth - CGFloat(4)) / 2
        cellHeight = collectionViewMaxHeight
    } else if (count == 3) {
        cellWidth = (collectionViewWidth - (CGFloat(4) * 2)) / 3
        cellHeight = collectionViewMaxHeight
    }
    
    return CGSize(width: cellWidth, height: cellHeight)
}

现在,我想确保集合视图的高度适合内容,但这是我努力实现它的地方。

我的集合视图位于堆栈视图内,所有约束都设置在堆栈视图的边缘。

我需要做什么来设置我的收藏视图的高度以适应内容?

标签: iosswiftuicollectionview

解决方案


推荐阅读