Ios 如何根据标签大小调整UICollectionView高度
在我的代码中,我创建了UICollectionView,它有页眉和页脚 我的页脚高度应该是动态的,取决于文本大小 文本可以是1行到100行 这是我的密码Ios 如何根据标签大小调整UICollectionView高度,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,在我的代码中,我创建了UICollectionView,它有页眉和页脚 我的页脚高度应该是动态的,取决于文本大小 文本可以是1行到100行 这是我的密码 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
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()
}
}
您可以向字符串扩展添加函数
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)
}
设置
label.numberOfLines=0
,您是否熟悉NSLayoutConstraints
/nslayoutAcho
?和的可能重复