如何在UICollectionView中动态调整标题视图的大小? [英] How can I dynamically resize a header view in a UICollectionView?

查看:472
本文介绍了如何在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.


  1. 在标题视图中设置 UILabel 有一个 numberOfLines 的值为0.这将让它自己调整大小。

  2. 将标题移出故事板并进入xib。

  3. collectionView(_:layout:referenceSizeForHeaderInSection:)实例化xib中的标头。我们将使用它来计算大小。

  4. 将标题设置为所需的宽度(在我的情况下是集合视图的宽度),并使用所需的文本和图像进行配置

  5. 致电 setNeedsLayout layoutIfNeeded

  6. 使用 systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)来计算高度。

  7. 将高度和宽度返回为CGSize

  1. Set the UILabel in the header view to have a numberOfLines value of 0. This will let it resize itself.
  2. Move the header out of the storyboard and into a xib.
  3. In collectionView(_:layout:referenceSizeForHeaderInSection:) instantiate a header from the xib. We'll use it to compute a size.
  4. 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
  5. Call setNeedsLayout and layoutIfNeeded.
  6. Use systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) to compute the height.
  7. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆