Single row CollectionView with UICollectionViewDelegateFlowLayout and constraints

35 Views Asked by At

I would like to have a single row collection view at the bottom of the screen with a text field on top of it. Red rectangle is the text field and the green one is the collection view. enter image description here

This is my setup code:

    view.addSubview(queryTextField)
    view.addSubview(suggestionsCollectionView)
    
    NSLayoutConstraint.activate([
        queryTextField.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
        queryTextField.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
        queryTextField.bottomAnchor.constraint(equalTo: suggestionsCollectionView.topAnchor),
        
        suggestionsCollectionView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
        suggestionsCollectionView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
        suggestionsCollectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
        suggestionsCollectionView.heightAnchor.constraint(equalToConstant: 160)
    ])
...
private func createCollectionViewLayout() -> UICollectionViewCompositionalLayout {
    return UICollectionViewCompositionalLayout { (_, _) -> NSCollectionLayoutSection? in
        // item
        let item = NSCollectionLayoutItem(
            layoutSize: NSCollectionLayoutSize(
                widthDimension: .fractionalWidth(1/3),
                heightDimension: .fractionalHeight(1)
            )
        )
        item.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 8)
        
        // group
        let group = NSCollectionLayoutGroup.horizontal(
            layoutSize: NSCollectionLayoutSize(
                widthDimension: .fractionalWidth(1),
                heightDimension: .absolute(140)
            ),
            repeatingSubitem: item,
            count: 3
        )
        group.contentInsets = NSDirectionalEdgeInsets(top: 16, leading: 0, bottom: 16, trailing: 0)
        
        // section
        let section = NSCollectionLayoutSection(group: group)
        section.orthogonalScrollingBehavior = .continuous
        section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20)
        
        // return
        return section
    }
}

I would like to achieve this layout without setting a height constraint on the collection view. I am already specifying the group height heightDimension: .absolute(140) so I expect the collection view to be able to calculate it on its own. How can I achieve this?

0

There are 0 best solutions below