gpt4 book ai didi

ios - 如何调整 UICollectionView 的高度为 UICollectionView 内容大小的高度?

转载 作者:IT王子 更新时间:2023-10-29 04:59:27 25 4
gpt4 key购买 nike

在本例中,我希望 UICollectionView(红色的)缩小到内容大小的高度 UICollectionViewCells(黄色的),因为有很多空白空间。我尝试的是使用:

override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}

override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}

但是return self.collection.contentSize总是返回(width, 0)由于这个原因,它缩小到高度值 30(我在 XIB 文件中设置的高度值,尽管我有 constaint >= 30)。

enter image description here

最佳答案

我建议如下:

  1. Add a height constraint to your collection view.
  2. Set its priority to 999.
  3. Set its constant to any value that makes it reasonably visible on the storyboard.
  4. Change the bottom equal constraint of the collection view to greater or equal.
  5. Connect the height constraint to an outlet.
  6. Every time you reload the data on the collection view do the following:

您可能还想通过将其添加到内容大小来考虑 Collection View 的 Inset。

代码示例:

CGFloat height = myCollectionView.collectionViewLayout.collectionViewContentSize.height
heightConstraint.constant = height
self.view.setNeedsLayout() Or self.view.layoutIfNeeded()

说明:Extra,看懂了就不用看了。很明显!!

UI 将尝试反射(reflect)所有约束,无论它们的优先级是什么。由于存在优先级较低的(999) 的高度约束,以及类型大于或等于的底部约束。每当高度约束常量设置为小于父 View 高度的值时, Collection View 将等于给定高度,从而实现两个约束。

但是,当高度约束常量设置为大于父 View 高度的值时,这两个约束都无法实现。因此,只有具有更高优先级的约束才会被实现,即大于或等于底部约束。

以下只是经验的猜测。因此,它实现了一个约束。但是,它还尝试使结果 UI 中针对其他未实现的较低优先级约束的错误 尽可能低。因此, Collection View 的高度将等于父 View 的大小。

关于ios - 如何调整 UICollectionView 的高度为 UICollectionView 内容大小的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42437966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com