dynamic height of UICollectionView (horizontal scrolling) based on cell height

Viewed 677

I've got the following situation:

A collectionView inside a containerView that sits below the navigationBar. The view is set up programmatically (no xib).

collectionView constraints

I want to place the containerView in a way that it does not need a height constraint. Is that possible? The containerView should get it's height based on the constraints in the collectionView cells.

Code:

This is the function which lays out the containerView inside the viewController:

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)
    ])
}

Inside the containerView (which is a subclass of UIView), the collectionView is set up like that (called in the init of that class):

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
}

When I do it like that, the collectionView is not visible. It only shows up when I add a height constraint with a specific constant to the containerView (inside the setUpContainerView function). The problem is, that I don't know that height. I would have to set that height to 10+10+50 = 70 manually. But I want to make the containerView get it's size based on the collectionView cell constraints. Is that possible?

0 Answers
Related