gpt4 book ai didi

ios - 动态计算 collectionView 单元格高度

转载 作者:行者123 更新时间:2023-11-28 06:31:06 24 4
gpt4 key购买 nike

我目前正在尝试动态计算 UICollectionViewCell 的高度,但使用的是 UILabel(动态属性)和单元格的当前高度。通过获取单元格内标签的 sizeThatFits 高度并将该值添加到单元格的原始高度来计算高度。由于某种原因,这总是在 sizeForItemAt 中返回 0。我很确定问题是在创建单元格之前正在计算大小,因此将始终返回 0。这附近有什么吗? (单元格的 UI 是在类本身中创建的,而不是在 celllForItemAt 中创建的,这也可能是个问题吗?)

  var descHeight: CGFloat = 0

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "desc", for: indexPath) as! ImageDescCell
descHeight = cell.descriptionLbl.sizeThatFits(cell.frame.size).height + cell.bounds.height
return cell
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let w = collectionView.bounds.width
return CGSize(width: w, height: descHeight)
}

最佳答案

NSAttributedString 可以告诉你一个实例有多大,给定一个界限。因此,假设您知道标签的宽度并且知道文本是什么以及它的属性是什么,您就可以在不创建标签的情况下获得尺寸:

let width = CGFloat(200)
let attributedString = NSAttributedString(string: "Test", attributes: [NSFontAttributeName : UIFont(name: "Helvetica", size: 18)!])
let boundingRect = attributedString.boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)

关于ios - 动态计算 collectionView 单元格高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40331420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com