UICompositionalLayout实现自适应宽度横向Cell出现跳页问题如何解决
问题原因
你当前的异常是横向滚动组的宽度配置错误导致的:你给group设置的宽度是.fractionalWidth(1),即默认占满整个collectionView的可视宽度,系统会自动把超过单屏宽度的cell拆分到新的同宽group中,就出现了类似翻页、最后一个cell被挤到下一页的效果。
修改方案
只需要把group的宽度维度从.fractionalWidth(1)改为.estimated(合理预估值),让group的宽度可以根据内部cell的总宽度自适应撑开即可解决问题,修改后的完整代码如下:
fileprivate func createNavigationButtonSection(using section: HomeSection) -> NSCollectionLayoutSection { let estimatedHeight: CGFloat = 40 let estimatedWidth: CGFloat = 100 let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(estimatedWidth), heightDimension: .estimated(estimatedHeight)) let item = NSCollectionLayoutItem(layoutSize: itemSize) item.edgeSpacing = NSCollectionLayoutEdgeSpacing(leading: nil, top: nil, trailing: .fixed(8), bottom: nil) // 仅修改这一行:group宽度改为预估,不需要占满整屏 let groupSize = NSCollectionLayoutSize(widthDimension: .estimated(estimatedWidth), heightDimension: .estimated(estimatedHeight)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) let section = NSCollectionLayoutSection(group: group) section.orthogonalScrollingBehavior = .continuous // 建议补充trailing间距,避免最后一个cell贴边 section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16) return section }
补充注意事项
- 要确保cell内部约束正确:文本标签的水平方向
contentHugging优先级设置为252以上,避免cell被异常拉伸 - 你已经设置了
orthogonalScrollingBehavior = .continuous,该配置不需要调整
内容的提问来源于stack exchange,提问作者David Henry
相关产品推荐
相关产品推荐

