Dynamic UICollectionView header size based on UILabel Dynamic UICollectionView header size based on UILabel swift swift

Dynamic UICollectionView header size based on UILabel


This is how I did it:

let labels = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ac lorem enim. Curabitur rhoncus efficitur quam, et pretium ipsum. Nam eu magna at velit sollicitudin fringilla nec nec nisi. Quisque nec enim et ipsum feugiat pretium. Vestibulum hendrerit arcu ut ipsum gravida, ut tincidunt justo pellentesque. Etiam lacus ligula, aliquet at lorem vel, ullamcorper commodo turpis. Nullam commodo sollicitudin mauris eu faucibus.","Lorem ipsum dolor","Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ac lorem enim. Curabitur rhoncus efficitur quam, et pretium ipsum. Nam eu magna at velit sollicitudin fringilla nec nec nisi. Quisque nec enim et ipsum feugiat pretium."]

The basic idea is to create an identical UILabel to the one that will be shown in the section header. That label will be used to set the desired size for the header in the referenceSizeForHeaderInSection method.

I have a label outlet called label in my UICollectionReusableView subclass (MyHeaderCollectionReusableView), which I use for my section header view by assigning it in the storyboard (setting "MyHeader" as Reuse Identifier for the section view). That mentioned label has the horizontal and vertical space constraints to the section header borders in order to autolayout correctly.

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {        return 3    }override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {        let headerView =        collectionView.dequeueReusableSupplementaryViewOfKind(kind,            withReuseIdentifier: "MyHeader",            forIndexPath: indexPath)            as MyHeaderCollectionReusableView        headerView.label.text = labels[indexPath.section]        return headerView    }func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {        // that -16 is because I have 8px for left and right spacing constraints for the label.        let label:UILabel = UILabel(frame: CGRectMake(0, 0, collectionView.frame.width - 16, CGFloat.max))        label.numberOfLines = 0        label.lineBreakMode = NSLineBreakMode.ByWordWrapping       //here, be sure you set the font type and size that matches the one set in the storyboard label        label.font = UIFont(name: "Helvetica", size: 17.0)        label.text = labels[section]        label.sizeToFit()// Set some extra pixels for height due to the margins of the header section.  //This value should be the sum of the vertical spacing you set in the autolayout constraints for the label. + 16 worked for me as I have 8px for top and bottom constraints.        return CGSize(width: collectionView.frame.width, height: label.frame.height + 16)    }


Like the questioner, I had a UICollectionView that contained a header with a single label, whose height I wanted to vary. I created an extension to UILabel to measure the height of a multiline label with a known width:

public extension UILabel {    public class func size(withText text: String, forWidth width: CGFloat) -> CGSize {        let measurementLabel = UILabel()        measurementLabel.text = text        measurementLabel.numberOfLines = 0        measurementLabel.lineBreakMode = .byWordWrapping        measurementLabel.translatesAutoresizingMaskIntoConstraints = false        measurementLabel.widthAnchor.constraint(equalToConstant: width).isActive = true        let size = measurementLabel.systemLayoutSizeFitting(UILayoutFittingCompressedSize)        return size    }}

Note: the above is in Swift 3 syntax.

Then I implement the header size method of UICollectionViewDelegateFlowLayout as:

extension MyCollectionViewController : UICollectionViewDelegateFlowLayout {    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {        let text = textForHeader(inSection: section)        var size =  UILabel.size(withAttributedText: text, forWidth: collectionView.frame.size.width)        size.height = size.height + 16        return size    }}

The work of calculating the header size is delegated to the above UILabel extension. The +16 is a experimentally derived fixed offset (8 + 8) that is based on margins and could be obtained programmatically.

All that's needed in the header callback is just to set the text:

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {    if kind == UICollectionElementKindSectionHeader, let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as?  MyCollectionHeader {        let text = textForHeader(inSection: section)        headerView.label.text = text        return headerView    }    return UICollectionReusableView()}


The idea is to have a template header instance in memory to calculate the desired height before creating the result header view. You should move your section header view to a separate .nib file, setup all autolayout constraints and instantiate the template in your viewDidLoad method like this:

class MyViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {  @IBOutlet var collectionView : UICollectionView?  private var _templateHeader : MyHeaderView  override func viewDidLoad() {    super.viewDidLoad()    let nib = UINib(nibName: "HeaderView", bundle:nil)    self.collectionView?.registerNib(nib, forCellWithReuseIdentifier: "header_view_id")    _templateHeader = nib.instantiateWithOwner(nil, options:nil)[0] as! MyHeaderView  }}

Then you will be able to calculate the header size (height in my example) in your flow layout delegate method:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {    _templateHeader.lblTitle.text = "some title here"    _templateHeader.lblDescription.text = "some long description"    _templateHeader.setNeedsUpdateConstraints();    _templateHeader.updateConstraintsIfNeeded()    _templateHeader.setNeedsLayout();    _templateHeader.layoutIfNeeded();    let computedSize = _templateHeader.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)    return CGSizeMake(collectionView.bounds.size.width, computedSize.height);}

And then create and return your regular header view as always, since you have already calculated its size in flow layout delegate method:

func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {    switch kind {    case UICollectionElementKindSectionHeader:        let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "header_view_id", forIndexPath: indexPath) as! MyHeaderView        headerView.lblTitle.text = "some title here"        headerView.lblDescription.text = "some long description"        headerView.setNeedsUpdateConstraints()        headerView.updateConstraintsIfNeeded()        headerView.setNeedsLayout()        headerView.layoutIfNeeded()        return headerView    default:        assert(false, "Unexpected kind")    }}

Forgot to say about one important moment - your header view should have an autolayout constraint on its contentView to fit the collection view width (plus or minus the desired margins).