1

In my code I have created UICollectonView which has header and footer.

My footer height should be dynamic depend on the text size.

Text can be from 1 line to 100 line.

Here is my code.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width:collectionView.frame.size.width, height:50.0)
    }

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        switch kind {                        
            case UICollectionElementKindSectionFooter:
                let footer = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "SectionFooterCollectionReusableView", for: indexPath) as! SectionFooterCollectionReusableView

                footer.lblDescription.text = composition?.desc
                return footer


            default: return UICollectionReusableView()
        }        
    }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
pmb
  • 2,327
  • 3
  • 30
  • 47
  • Set `label.numberOfLines = 0`, are you familiar with `NSLayoutConstraints` / `NSLayoutAnchor` ? – user1046037 May 23 '17 at 11:26
  • 2
    possible duplicate of https://stackoverflow.com/questions/25642493/dynamic-uicollectionview-header-size-based-on-uilabel and https://stackoverflow.com/questions/39825290/make-uicollectionview-header-dynamic-height – elk_cloner May 23 '17 at 11:39

1 Answers1

2

You can add function to String extension

extension String {

    func heightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin,
            attributes: [NSFontAttributeName: font], context: nil)
        return boundingBox.height
    }
}

then in your method calculate text height

func collectionView(_ collectionView: UICollectionView,
    layout  collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
    if let string = composition?.desc {
        let height = string.heightWithConstrainedWidth(width, font: font)
        //calculate needed height
        return CGSize(width:collectionView.frame.size.width, height:neededHeight)
    }
    return CGSize(width:collectionView.frame.size.width, height:50.0)
}
Taras Chernyshenko
  • 2,729
  • 14
  • 27