【问题标题】:UICollectionView Self Sizing CellsUICollectionView 自调整大小的单元格
【发布时间】:2019-01-08 05:51:51
【问题描述】:

所以我想弄清楚如何自行调整集合视图单元格的大小。所以我有一个 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 文件的情况下调整单元格的大小?谢谢

【问题讨论】:

  • 它可能会有所帮助,请查看此链接,stackoverflow.com/questions/25895311/…
  • “这会导致我的应用程序崩溃” ...如果您想使用后一种技术并且如果它崩溃了,您必须告诉我们它在哪一行崩溃了,出现了什么控制台等。如果没有这些信息,我们将无法轻松诊断...
  • 看看这个帖子medium.com/dev-genius/…

标签: swift uicollectionview uicollectionviewflowlayout


【解决方案1】:

假设您在单元格 NIB/原型中有约束,您希望将 itemSize 设置为 .automaticSize

if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
    layout.estimatedItemSize = CGSize(width: view.frame.width, height: 100)
    layout.itemSize = UICollectionViewFlowLayout.automaticSize
}

您尚未分享设置的位置,但如果在 viewDidLoad 中完成,view.frame.width 可能不是您认为的那样。您需要仔细检查...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 2020-06-26
    • 2015-02-26
    • 1970-01-01
    • 2020-07-07
    • 2013-02-24
    • 1970-01-01
    • 2015-09-16
    相关资源
    最近更新 更多