是否可以通过其动态单元格高度更改集合视图的高度?如果可能,我们应该使用哪种委托方法?

时间:2018-12-21 11:19:49

标签: ios swift

我必须使用其动态单元格高度更改集合视图的高度。单元格高度取决于其内容,并且该单元格高度应更新集合视图的高度。

1 个答案:

答案 0 :(得分:0)

如果您使用的是UICollectionViewFlowLayout,则可以对iOS 8及更高版本中的UICollectionView和UITableView功能使用自定义大小的单元格。此功能有助于根据单元格中设置的内容和约束条件动态设置单元格的高度。

您需要执行两步设置,以使自定义尺寸的单元正常工作。

1。在UICollectionViewFlowLayout上设置EstimatedItemSize:

//for storyboard:

if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
    flowLayout.estimatedItemSize = CGSize(width: UIScreen.main.bounds.width, height: 100)
}

//using code:

let flowLayout = UICollectionViewFlowLayout()
let collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: flowLayout)
flowLayout.estimatedItemSize = CGSize.init(width: UIScreen.main.bounds.width, height: 100)

2。使用Autolayout来配置自定义UICollectionView单元或实现 preferredLayoutAttributesFittingAttributes在您的自定义单元格中

var isHeightCalculated:Bool = false

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    //Exhibit A - We need to cache our calculation to prevent a crash.
    if !isHeightCalculated {
        setNeedsLayout()
        layoutIfNeeded()
        let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
        var newFrame = layoutAttributes.frame
        newFrame.size.width = CGFloat(ceilf(Float(size.width)))
        layoutAttributes.frame = newFrame
        isHeightCalculated = true
    }
    return layoutAttributes
}

阅读stackoverflowblog,以获取有关如何使用自动布局来自动调整单元大小的更多信息。