ios - UICollectionView:使用 UIStackView 的动态单元格高度

标签 ios swift uicollectionview uistackview

我有一个 Storyboard ,由一个 UICollectionView 和多个单元格组成,每个单元格的高度各不相同。第一个单元格采用 UICollectionViewDelegateFlowLayout 的高度:

func collectionView(collectionView: UICollectionView,
        layout collectionViewLayout: UICollectionViewLayout,
        sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize

.. 但我希望第二个单元格更短。 我在单元格内的“主”UIStackView 中放置了两个 UIStackViews,每个内部 UIStackViews 都有一个或多个标签,例如这个:

cell
--> stackView (master)
    --> stackView (1)
        --> label
    --> stackView (2)
        --> label
        --> label (etc)

.. 希望 UIStackView 可以使单元格高度动态,但事实并非如此。它像以前一样从 UICollectionViewDelegateFlowLayout 获取高度。

我应该怎么做?

最佳答案

您需要计算 CollectionViewCell 的内容大小并将其返回给 sizeForItemAt 函数。

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

    // Create an instance of the `FooCollectionViewCell`, either from nib file or from code.
    // Here we assume `FooCollectionViewCell` is created from a FooCollectionViewCell.xib
    let cell: FooCollectionViewCell = UINib(nibName: "FooCollectionViewCell", bundle: nil)
        .instantiate(withOwner: nil, options: nil)
        .first as! FooCollectionViewCell

    // Configure the data for your `FooCollectionViewCell`
    cell.stackView.addArrangedSubview(/*view1*/)
    cell.stackView.addArrangedSubview(/*view2*/)

    // Layout the collection view cell
    cell.setNeedsLayout()
    cell.layoutSubviews()

    // Calculate the height of the collection view based on the content
    let size = cell.contentView.systemLayoutSizeFitting(
        CGSize(width: collectionView.bounds.width, height: 0),
        withHorizontalFittingPriority: UILayoutPriorityRequired,
        verticalFittingPriority: UILayoutPriorityFittingSizeLevel)

    return size
}

这样,您将拥有动态单元格高度 UICollectionView


补充说明:

  1. 对于 Collection View 单元格的配置,您可以在 FooCollectionViewCell 上创建一个辅助函数 func configure(someData: SomeData) 以便共享代码在 cellForItemAt 函数和 sizeForItemAt 函数之间。

    // Configure the data for your `FooCollectionViewCell`
    cell.stackView.addArrangedSubview(/*view1*/)
    cell.stackView.addArrangedSubview(/*view2*/)
    
  2. 对于这两行代码,似乎只有当 UICollectionViewCell 包含垂直 UIStackView 作为 subview 时才需要(可能是 Apple 的错误)。

    // Layout the collection view cell
    cell.setNeedsLayout()
    cell.layoutSubviews()
    

关于ios - UICollectionView:使用 UIStackView 的动态单元格高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33965415/

相关文章:

ios - 如何确定当前的iPhone/设备型号?

ipad - UICollectionView 在覆盖 scrollViewWillEndDragging 时并不总是动画减速

ios - 状态栏下的 CollectionView 标题内容

ios - -[MPVolumeView initWithFrame :style] not called on main thread when loading UIWebView

iOS:同步来自相机和运动数据的帧

ios - 自定义 SKShapeNode 子项未出现

ios - UICollectionViewFlowLayout 子类在滚动和重新加载时崩溃访问超出范围的数组

ios - iAd 卡住游戏场景

ios - 无法使用 Firebase 检索最近添加的值

ios - 复合过滤器数组的 Realm 查询