如何根据内容设置 collectionview 单元格宽度?

How to set collectionview cell width based on content?

我有一个水平滚动的collectionview.The单元格包含一个label.I想根据label.How的内容调整单元格宽度可以实现吗?请帮助我这个

使用此函数计算标签宽度

func widthOfString(usingFont font: UIFont) -> CGFloat {
     let fontAttributes = [NSFontAttributeName: font]
     let size = self.size(attributes: fontAttributes)
     return size.width
}

使用UICollectionViewDelegateFlowLayout设置collectionViewCell

的大小
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = //calculated width of label from func
   return CGSize(width: width, height:requiredHeight)
}

而不是调用 sizeforitem

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

 return CGSize(width: 100, height : 100)
}

您可以将布局属性设置为根据标签内容自动调整大小

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.estimatedItemSize = CGSize(width: 100, height: 30)