How can I dynamically resize the header in a UICollectionView?

I have a header (UICollectionReusableCell) in a UICollectionView whose height should be variable. How can I resize it to fit the height of its contents?

I do not need to support iOS 7, and Autolayout solutions are preferable (if they exist).

+3
source share
2 answers

This is how I solved it. I wish it was more elegant.

  • Set the UILabeltitle view numberOfLinesto 0. This will allow you to resize.
  • Move the title from the storyboard and to xib.
  • collectionView(_:layout:referenceSizeForHeaderInSection:) xib. .
  • ( )
  • setNeedsLayout layoutIfNeeded.
  • systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) .
  • CGSize

:

  • xib, dequeuReusableSupplementaryViewOfKind systemLayoutSizeFittingSize(UILayoutFittingCompressedSize) .

  • , . .

+7

-

  • .
  • %

-

    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
}
0

Source: https://habr.com/ru/post/1652819/


All Articles