在我的代码中,我创建了具有页眉和页脚的UICollectonView。
我的页脚高度应该是动态的,具体取决于文本大小。
文字可以是1行到100行。
这是我的代码。
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()
}
}
答案 0 :(得分:1)
您可以向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
}
}
然后在你的方法中计算文字高度
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)
}