Constraining a collection view under a normal UIView

58 Views Asked by At

I have an UIView that shows up fine. I am trying to have a collectionView to show up under it. Both elements show up fine when called on their own, but when I call both I get constraining errors.

In my view I did load:

    configureStatsView()
    configureCollectionView()

ConfigureStatsView:

    private func configureStatsView() {

    view.addSubview(statsView)
    statsView.translatesAutoresizingMaskIntoConstraints = false
    statsView.backgroundColor = .systemRed

    let padding: CGFloat    = 20

    NSLayoutConstraint.activate([

        statsView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
        statsView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding),
        statsView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding),
        statsView.heightAnchor.constraint(equalToConstant: 180),

    ])
}

ConfigureCollectionView:

    private func configureCollectionView() {

    collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: UIHelper.createThreeColumnFlowLayout(in: view))
    view.addSubview(collectionView)
    collectionView.delegate = self
    collectionView.backgroundColor = .systemBackground
    collectionView.register(CustomCell.self, forCellWithReuseIdentifier: CustomCell.resuseID)

    let padding: CGFloat    = 20

    NSLayoutConstraint.activate([

        collectionView.topAnchor.constraint(equalTo: statsView.bottomAnchor, constant: padding),
        collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: padding),
        collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -padding),
        collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),

    ])
}
1

There are 1 best solutions below

0
Shehata Gamal On BEST ANSWER

You miss

collectionView.translatesAutoresizingMaskIntoConstraints = false