lectionView的高度调整为UICollectionVie

lectionView的高度调整为UICollectionVie

本文介绍了如何将UICollectionView的高度调整为UICollectionView的内容大小的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,我希望UICollectionView(红色的)缩小到内容大小的高度UICollectionViewCells(黄色的),因为有很多空白空间.我尝试使用的是:

I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:

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始终返回(宽度,0)出于这个原因,它会缩小到高度30的值(我在XIB文件中为高度设置的值,尽管我的约束> = 30).

but return self.collection.contentSize always return (width, 0)and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).

推荐答案

我建议以下内容:

  1. 向收藏夹视图添加高度限制.
  2. 将其优先级设置为999.
  3. 将其常数设置为使其在情节提要板上合理可见的任何值.
  4. 将集合视图的底部相等约束更改为更大或相等.
  5. 将高度约束连接到插座.
  6. 每次在集合视图上重新加载数据时,请执行以下操作:

您可能还需要通过将其添加到内容大小中来考虑集合视图的插图.

代码示例:

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

说明:额外,如果您了解它,则不必阅读.显然!!

无论优先级是什么,UI都将尝试反映所有约束.由于高度约束的优先级较低,为(999),而底部约束的优先级大于或等于.只要将高度限制常数设置为小于父视图高度的值,则收集视图将等于给定高度,从而实现两个限制.

The UI will try to reflect all the constraints no matter what are their priorities. Since the height constraint has lower priority of (999), and a bottom constraint of type greater or equal. whenever, the height constraint constant is set to a value less than the parent view height the collection view will be equal to the given height, achieving both constraints.

但是,当高度限制常数设置为大于父视图高度的值时,两个限制都无法实现.因此,只能实现优先级更高的约束,即更高或等于最低约束的约束.

But, when the height constraint constant set to a value more than the parent view height both constraints can't be achieved. Therefore, only the constraint with the higher priority will be achieved which is the greater or equal bottom constraint.

以下内容仅是根据经验得出的猜测.因此,它达到一个常数.但是,它还会尝试使结果用户界面中的错误为其他未实现的较低优先级约束尽可能低.因此,集合视图的高度将等于父视图的大小.

The following is just a guess from an experience. So, it achieves one constrant. But, it also tries to make the error in the resulted UI for the other un-achieved lower priority constraint as lowest as possible. Therefore, the collection view height will be equal to the parent view size.

这篇关于如何将UICollectionView的高度调整为UICollectionView的内容大小的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:01