Reputation: 2327
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()
}
}
Upvotes: 1
Views: 467
Reputation: 2829
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)
}
Upvotes: 2