所以我想弄清楚如何自行调整集合视图单元格的大小。所以我有一个 ViewController,我在 ViewController 中拖了一个 collectionView。我没有使用 xib 文件,我使用的是原型单元。现在我似乎无法弄清楚如何自行调整单元格的大小。它不像表格视图那么容易。我已经尝试了以下我发现的方法。
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = CGSize(width: view.frame.width, height: 100)
layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
然后我找到了另一个创建 dummyCell 的,看起来像这样。虽然这会使我的应用程序崩溃。
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 50)
let dummyCell = CommentCell(frame: frame)
let comment = comments[indexPath.item]
print(comment.text)
dummyCell.comment = comment
dummyCell.layoutIfNeeded()
let targetSize = CGSize(width: view.frame.width, height: 1000)
let estimateSize = dummyCell.systemLayoutSizeFitting(targetSize)
let height = max(45 + 8 + 8, estimateSize.height)
return CGSize(width: view.frame.width, height: height)
}
所以我需要一个集合视图控制器而不是视图控制器。我如何能够在不使用 collectionViewController 或 nib 文件的情况下调整单元格的大小?谢谢