UICollectionViewFlowLayout 问题

UICollectionViewFlowLayout Issue

我曾尝试创建可自行调整大小的 collectionView cell,但我的标签不想扩展他的高度并变成多行,相反标签只是在一行中,我的单元格超出了集合视图框架。我创建了自己的自定义 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
    }
}

您必须计算文本高度并将其传递给您的 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 - 这是单元格中文本宽度的重要值。好好算一算