您需要将集合视图高度限制为内容的高度:
我在以下代码中使用 SnapKit。
首先将集合视图边缘约束到其父视图:
private func constrainViews() {
collectionView?.translatesAutoresizingMaskIntoConstraints = true
collectionView?.snp.makeConstraints { make in
make.edges.equalToSuperview()
heightConstraint = make.height.equalTo(0).constraint
}
}
接下来计算高度并将高度设置为高度约束偏移。我让流布局完成工作,然后根据最后一个布局属性的底部边缘计算高度:
override func viewDidLayoutSubviews() {
guard
let collectionView = collectionView,
let layout = collectionViewLayout as? UICollectionViewFlowLayout
else {
return
}
let sectionInset = layout.sectionInset
let contentInset = collectionView.contentInset
let indexPath = IndexPath(item: tags.count, section: 0)
guard let attr = collectionViewLayout.layoutAttributesForItem(at: indexPath) else {
return
}
// Note sectionInset.top is already included in the frame's origin
let totalHeight = attr.frame.origin.y + attr.frame.size.height
+ contentInset.top + contentInset.bottom
+ sectionInset.bottom
heightConstraint?.update(offset: totalHeight)
}
请注意,在示例中,我的项目tags
计数中始终没有包含一个特殊标签,因此该行:
let indexPath = IndexPath(item: tags.count, section: 0)
需要像if items.count > 0 ... let indexPath = IndexPath(item: tags.count - 1, section: 0)
大多数其他代码一样。