在普通 UIView 下约束集合视图

Constraining a collection view under a normal UIView

我有一个显示良好的 UIView。我想让一个 collectionView 显示在它下面。这两个元素在单独调用时都显示良好,但是当我同时调用这两个元素时,我遇到了约束错误。

在我看来我确实加载了:

    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),

    ])
}

配置集合视图:

    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),

    ])
}

你错过了

collectionView.translatesAutoresizingMaskIntoConstraints = false