func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
func textSize(text: String) -> CGSize {
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17)]
return text.size(withAttributes: attributes)
}
let locationText = locationLabel.text ?? ""
let padding: CGFloat = 16
let textSize = textSize(text: locationText)
let cellWidth = textSize.width + padding
return CGSize(width: cellWidth, height: collectionView.frame.height / 2.1)
}
这是我使用的代码。