提问人:smeshko 提问时间:11/15/2023 更新时间:11/15/2023 访问量:20
具有 UICollectionViewDelegateFlowLayout 和约束的单行 CollectionView
Single row CollectionView with UICollectionViewDelegateFlowLayout and constraints
问:
我希望在屏幕底部有一个单行集合视图,并在其顶部有一个文本字段。红色矩形是文本字段,绿色矩形是集合视图。
这是我的设置代码:
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
}
}
我希望在不对集合视图设置高度约束的情况下实现此布局。我已经指定了组高度,因此我希望集合视图能够自行计算它。我怎样才能做到这一点?heightDimension: .absolute(140)
答: 暂无答案
评论
UICollectionView