动态计算 collectionView 单元格高度

Calculating collectionView cell height dynamically

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

swift-3.0

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
   let width = self.collectionView.frame.size.width
   let Height = self.view.frame.size.height - 64 // 64 is a navigation bar height minus.
   let cellSize:CGSize = CGSize(width: width, height: Height )
   return cellSize
}