我如何dynamic调整UICollectionView中的标题视图?

我有一个UICollectionView中的头(UICollectionReusableCell),其高度需要是可变的。 我怎么能根据内容的高度来调整自己?

我不需要支持iOS 7,Autolayout解决scheme是可取的(如果存在的话)。

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

  1. 将标题视图中的UILabel设置为numberOfLines值为0.这将允许它自己resize。
  2. 将标题移出故事板并放入xib。
  3. collectionView(_:layout:referenceSizeForHeaderInSection:)实例化xib中的头文件。 我们将使用它来计算大小。
  4. 设置标题为所需的宽度(在我的情况下集合视图的宽度),并configuration所需的文字和图像
  5. 调用setNeedsLayoutlayoutIfNeeded
  6. 使用systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)来计算高度。
  7. 以CGSize的forms返回高度和宽度

笔记:

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

  • 标题视图必须能够计算正确的高度只知道它的内容和所需的宽度。 这花了一些摆弄的约束。

这将是我的方法 –

  1. 为您的标题和内容创build出口。
  2. 获取你的内容的高度
  3. 将头部的高度设置为内容的百分比

在你的视图控制器 –

  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 }