我想UICollectionView(红色的)缩小到内容大小的高度,在这种情况下UICollectionViewCells(黄色的)因为有很多空的空间.我尝试的是使用: override func layoutSubviews() { super.layoutSubviews() if !__CGSizeEqual
override func layoutSubviews() { super.layoutSubviews() if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) { self.invalidateIntrinsicContentSize() } } override var intrinsicContentSize: CGSize { return self.collection.contentSize }
但返回self.collection.contentSize总是返回(宽度,0)
并且由于这个原因,它收缩到高度值30(我在XIB文件中为高度设置的值,尽管我有constaint> = 30).
- Add a height constraint to your collection view.
- Set its priority to 999.
- Set its constant to any value that makes it reasonably visible on the storyboard.
- Change the bottom equal constraint of the collection view to greater or equal.
- Connect the height constraint to an outlet.
- Every time you reload the data on the collection view do the following:
代码示例:
CGFloat height = myCollectionView.collectionViewLayout.collectionViewContentSize.height heightConstraint.constant = height self.view.setNeedsLayout() Or self.view.layoutIfNeeded()
说明:额外,如果您理解,则无需阅读.明显!!
UI将尝试反映所有约束,无论它们的优先级如何.由于高度约束的优先级较低(999),而底部约束的类型大于或等于.每当高度约束常量设置为小于父视图高度的值时,集合视图将等于给定高度,从而实现两个约束.
但是,当高度约束常量设置为大于父视图高度的值时,两个约束都无法实现.因此,只有具有较高优先级的约束才能实现,即较大或相等的底部约束.
以下只是一种体验的猜测.因此,它实现了一个常量.但是,它也会尝试使结果UI中的错误尽可能地低于其他未实现的较低优先级约束.因此,集合视图高度将等于父视图大小.