如何在 UICollectionView 中动态调整 header 视图的大小?

How can I dynamically resize a header view in a UICollectionView?

我在高度需要可变的 UICollectionView 中有 header(一个 UICollectionReusableCell)。如何让它根据其内容的高度自行调整大小?

不需要支持iOS 7,自动布局解决方案更可取(如果存在的话)。

这是我的方法 -

  1. 为您的 header 和您的内容创建渠道。
  2. 获取内容的高度
  3. 将 header 的高度设置为内容的百分比

在您的视图控制器中 -

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = yourCollectionView.dequeueReusableCellWithReuseIdentifier("YourCustomCell", forIndexPath: indexPath) as! YourCustomeCell
    ...
    cell.setUpCell()
    return cell
}

在您的视图单元格中 -

@IBOutlet weak var headerView: UIView!
@IBOutlet weak var contentView: UIView!
func setUpCell() {
    let percentageYouWant = 0.3
    let newFrame = CGRect(x: 0, y: 0, width: contentView * percentageYouWant, height: contentView * percentageYouWant)
    headerView.frame = newFrame
}

我就是这样解决的。我希望它更优雅。

  1. 将 header 视图中的 UILabel 设置为 numberOfLines 值为 0。这将让它自行调整大小。
  2. 将 header 移出情节提要并放入 xib。
  3. collectionView(_:layout:referenceSizeForHeaderInSection:)中从xib实例化一个header。我们将使用它来计算尺寸。
  4. 将 header 设置为所需的宽度(在我的例子中是 collection 视图的宽度),并使用所需的文本和图像对其进行配置
  5. 调用 setNeedsLayoutlayoutIfNeeded
  6. 使用systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)计算高度。
  7. Return 高度和宽度为 CGSize

备注:

  • 必须将 header 移出故事板并移入 xib,因为从 systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) 调用 dequeuReusableSupplementaryViewOfKind 会导致崩溃。

  • header 视图必须能够在知道其内容和所需宽度的情况下计算出正确的高度。这需要一些约束。