如何在UICollectionView中动态调整标题视图的大小? [英] How can I dynamically resize a header view in a UICollectionView?
问题描述
我在UICollectionView中有头(一个UICollectionReusableCell),其高度需要是可变的。如何根据内容的高度调整自身大小?
I have header (a UICollectionReusableCell) in a UICollectionView whose height needs to be variable. How can I have it resize itself according to the height of its contents?
我不需要支持iOS 7,而Autolayout解决方案是最好(如果存在的话)。
I do not need to support iOS 7, and Autolayout solutions are preferable (if they exist).
推荐答案
这就是我解决它的方法。我希望它更优雅。
This is how I solved it. I wish it was more elegant.
- 在标题视图中设置
UILabel
有一个numberOfLines
的值为0.这将让它自己调整大小。 - 将标题移出故事板并进入xib。
- 在
collectionView(_:layout:referenceSizeForHeaderInSection:)
实例化xib中的标头。我们将使用它来计算大小。 - 将标题设置为所需的宽度(在我的情况下是集合视图的宽度),并使用所需的文本和图像进行配置
- 致电
setNeedsLayout
和layoutIfNeeded
。 - 使用
systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
来计算高度。 - 将高度和宽度返回为CGSize
- Set the
UILabel
in the header view to have anumberOfLines
value of 0. This will let it resize itself. - Move the header out of the storyboard and into a xib.
- In
collectionView(_:layout:referenceSizeForHeaderInSection:)
instantiate a header from the xib. We'll use it to compute a size. - Set the header to the desired width (in my case the width of the collection view), and configure it with the desired text and images
- Call
setNeedsLayout
andlayoutIfNeeded
. - Use
systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
to compute the height. - Return the height and width as CGSize
注意:
-
标题必须移出故事板和xib,因为从
systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
调用dequeuReusableSupplementaryViewOfKind
会导致崩溃。
标题视图必须能够计算正确的高度,只知道其内容和所需的宽度。这需要一些摆弄约束。
The header view must be able to compute a correct height only knowing its content and the desired width. This took some fiddling with the constraints.
这篇关于如何在UICollectionView中动态调整标题视图的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!