我曾经尝试过创建自调整大小的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
}
}

发布于 2020-02-17 09:50:51
必须计算文本高度并将其传递给您的集合视图委托方法。
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 --这是单元格中文本宽度的重要值。算好了
https://stackoverflow.com/questions/60259452
复制相似问题