如何根据 UILabel 动态调整 CollectionViewCell 的大小

How to dynamically size CollectionViewCell as per UILabel

我正在创建一个 suggestion/tags 视图。这基本上是水平的 uicollectionview。我有一个自定义单元格,其中只有一个标签,没有自动调整大小或自动约束。我有一个数组 var tagsArray = ["Label", "A Long Label", "A very long label"],我在 collectionView 委托方法中使用它作为:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return tagsArray.count
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let size = (tagsArray[indexPath.row] as NSString).size(withAttributes: nil)
    return size
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCell", for: indexPath) as! TagCollectionViewCell
    cell.tagLabel.text = tagsArray[indexPath.row]
    return cell

}

第二个函数 collectionViewLayout 是我从堆栈溢出中选择的,但是当我 运行 它对 UILabel 没有影响。

这是输出:

您不需要计算要显示的字符串的大小。执行以下操作:

  1. 设置 collectionView 的高度等于标签的预期高度。
  2. tagLabelleadingtrailingtopbottom 约束设置为等于相应单元格的 contentView 约束。
  3. 删除 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 的实现。如果您不为 estimatedItemSize 使用自定义值,将自动计算单元格大小。如果您想确定,请将 (collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.estimatedItemSize = UICollectionViewFlowLayout.automaticSize 添加到设置所有视图的函数中。

您将看到以下结果: