自动调整 UICollectionView 的高度以适应其内容大小

24

我有一个UICollectionView和一个按钮,该按钮在集合视图中创建一个新的单元格。 我希望UICollectionView根据其内容大小调整其大小(当只有一两个单元格时,UICollectionView很短,如果有许多单元格,则UICollectionView足够大)。

我知道如何获取内容大小:

collectionView.collectionViewLayout.collectionViewContentSize

但是我不知道在哪里使用这个值。如果有人能帮我弄清楚如何使UICollectionView自动调整其高度,我将不胜感激。

更新:我在GitHub上发布了一个演示项目,描述了这个问题:https://github.com/avokin/PostViewer


发布了对类似问题的答案:https://dev59.com/wVgQ5IYBdhLWcg3wo1hE#67055114 - Matthew Quiros
这个回答解决了你的问题吗?如何调整UICollectionView的高度以匹配其内容大小? - Matthew Quiros
4个回答

6

我觉得您需要调整的不是内容大小,而是要减少集合视图所占用的屏幕空间,是吗?这将需要调整框架。内容大小包括屏幕以外(滚动)区域和屏幕上的视图。

我不知道是否有任何阻止您随时更改框架大小的东西:

collectionView.frame = CGRectMake (x,y,w,h);
[collectionView reloadData];

如果我理解你的意思正确的话。

1
我有这样的代码:cell.tagsCollection.frame = CGRectMake(frame.origin.x, frame.origin.y, size.width, size.height);。但在滚动collectionView.frame之前,高度和宽度为0,iOS忽略了我对这些属性的更改。 - AVokin
如何使单元格高度自适应内容 - Mansuu....

6

0

你需要将集合视图的高度限制为内容的高度:

我在以下代码中使用SnapKit。

首先将集合视图的边缘约束到其父视图:

private func constrainViews() {
    collectionView?.translatesAutoresizingMaskIntoConstraints = true

    collectionView?.snp.makeConstraints { make in
        make.edges.equalToSuperview()
        heightConstraint = make.height.equalTo(0).constraint
    }
}

接下来计算高度并将其设置为高度约束偏移量。我让流式布局完成工作,然后根据最后一个布局属性的底部边缘计算高度:
override func viewDidLayoutSubviews() {
    guard
        let collectionView = collectionView,
        let layout = collectionViewLayout as? UICollectionViewFlowLayout
    else {
        return
    }

    let sectionInset = layout.sectionInset
    let contentInset = collectionView.contentInset

    let indexPath = IndexPath(item: tags.count, section: 0)
    guard let attr = collectionViewLayout.layoutAttributesForItem(at: indexPath) else {
        return
    }

    // Note sectionInset.top is already included in the frame's origin
    let totalHeight = attr.frame.origin.y + attr.frame.size.height
        + contentInset.top + contentInset.bottom
        + sectionInset.bottom

    heightConstraint?.update(offset: totalHeight)
}

请注意,在这个例子中,我总是有一个特殊的标签没有包含在我的项目tags计数中,因此这一行代码:
let indexPath = IndexPath(item: tags.count, section: 0)

在大多数其他代码中,需要像这样的东西:if items.count > 0 ... let indexPath = IndexPath(item: tags.count - 1, section: 0)


0

更改UICollectionView框架的步骤:

  1. 如果您正在使用自动布局,请将“translatesAutoresizingMaskIntoConstraints”属性设置为YES,以用于collectioview的父视图。

  2. 然后按以下方式更新collectioview的框架:

    collectionView.frame = CGRectMake (x,y,w,h);
    [collectionView reloadData];
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接