我试图创建自动调整大小的collectionView cell
,但是我的标签不想扩大他的身高并变成多行,而是标签只一行了,而我的单元格超出了collectionView框架。我已经创建了自己的自定义UICollectionViewFlowLayout并尝试处理那里的所有内容。我做错了什么?期待您的回答,谢谢!
我的实现:
class VerticalLayout:UICollectionViewFlowLayout {
override func prepare() {
super.prepare()
self.scrollDirection = .vertical
self.minimumLineSpacing = 0
self.minimumInteritemSpacing = 0
self.estimatedItemSize = CGSize(width: UIScreen.main.bounds.width, height: 173)
self.sectionInset = .zero
}
}
答案 0 :(得分:2)
您必须计算文本高度并将其传递给您的collectionview委托方法
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let itemHeight: CGFloat = estimatedHeightForText(text: items[indexPath.item].text, fontSize: fontSize, fontWeight: fontWeight, width: widthForText) + someRawValue // here count height for cell
var itemWidth: CGFloat = someRawVal
return CGSize(width: itemWidth, height: itemHeight)
}
在这里算
func estimatedHeightForText(text: String, fontSize: CGFloat, fontWeight: UIFont.Weight, width: CGFloat) -> CGRect {
let size = CGSize(width: width, height: 1000)
let font = UIFont.systemFont(ofSize: fontSize, weight: fontWeight)
return NSString(string: text).boundingRect(with: size, options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [NSAttributedString.Key.font: font], context: nil)
}
UPD。 widthForText-这是单元格中文本宽度的重要值。正确计数