基于单元格高度的 UICollectionView 动态高度(水平滚动)

时间:2021-01-29 13:28:35

标签: ios swift uicollectionview autolayout

我遇到了以下情况:

位于导航栏下方的 containerView 内的 collectionView。视图以编程方式设置(无 xib)。

collectionView constraints

我想以不需要高度约束的方式放置 containerView。那可能吗? containerView 应该根据 collectionView 单元格中的约束获取它的高度。

代码:

这是在viewController中布置containerView的函数:

private func setUpContainerView() {
    view.addSubview(containerView)
    containerView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        containerView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        containerView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        containerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20)
    ])
}

在containerView(它是UIView的子类)内部,collectionView是这样设置的(在那个类的init中调用):

private func setUpCollectionView() {
    collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionViewFlowLayout())
    guard let collectionView = collectionView else { return }
    addSubview(collectionView)
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    NSLayoutConstraint.activate([
        collectionView.trailingAnchor.constraint(equalTo: self.trailingAnchor),
        collectionView.leadingAnchor.constraint(equalTo: self.leadingAnchor),
        collectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor),
        collectionView.topAnchor.constraint(equalTo: self.topAnchor)
    ])
    collectionView.delegate = self
    collectionView.dataSource = self
    registerCollectionViewNibs()
}

private func collectionViewFlowLayout() -> UICollectionViewFlowLayout{
    let flowLayout = UICollectionViewFlowLayout()
    flowLayout.scrollDirection = .horizontal
    flowLayout.minimumInteritemSpacing = 10
    flowLayout.minimumLineSpacing = 10
    flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
    return flowLayout
}

当我这样做时,collectionView 是不可见的。它仅在我向 containerView(在 setUpContainerView 函数内)添加具有特定常量的高度约束时才会显示。 问题是,我不知道那个高度。我必须手动将该高度设置为 10+10+50 = 70。但我想让 containerView 根据 collectionView 单元格约束获得它的大小。这可能吗?

0 个答案:

没有答案