Kev*_*ers 13 uikit uicollectionview uicollectionviewlayout swift
我的布局代码非常简单,您将在有关新组合布局的每个教程或文章中看到这一点。
func createLayout() -> UICollectionViewLayout {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
item.contentInsets = .init(top: 0, leading: 5, bottom: 0, trailing: 5)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.93), heightDimension: .fractionalHeight(1.0))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
section.orthogonalScrollingBehavior = .groupPagingCentered
let layout = UICollectionViewCompositionalLayout(section: section)
return layout
}
Run Code Online (Sandbox Code Playgroud)
当我启动应用程序时,单元格未正确居中。只有当我将单元格拖动最微小的量时,它才会弹到正确的位置。
前:
当我拖动它一点点后:
我还没有看到任何关于同样问题的问题。Twitter 或博客上没有人谈论它。不确定我在这里做错了什么?
小智 28
也许为时已晚,但这里有一个解决方法:
func createLayout() -> UICollectionViewLayout {
let layout = UICollectionViewCompositionalLayout { (sectionIndex, environment) -> NSCollectionLayoutSection? in
let sideInset: CGFloat = 5
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
item.contentInsets = .init(top: 0, leading: sideInset, bottom: 0, trailing: sideInset)
let groupWidth = environment.container.contentSize.width * 0.93
let groupSize = NSCollectionLayoutSize(widthDimension: .absolute(groupWidth), heightDimension: .fractionalHeight(1.0))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
// add leading and trailing insets to the section so groups are aligned to the center
let sectionSideInset = (environment.container.contentSize.width - groupWidth) / 2
section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: sectionSideInset, bottom: 0, trailing: sectionSideInset)
// note this is not .groupPagingCentered
section.orthogonalScrollingBehavior = .groupPaging
return section
}
return layout
}
Run Code Online (Sandbox Code Playgroud)
这是预期的行为。“居中”意味着单元格在滚动后捕捉到中心。在进行任何滚动之前,整个组会一直滚动到右侧。您的组只有0.93
分数宽度,因此差异很小。当分数宽度较小时,效果就不那么难看了。
归档时间: |
|
查看次数: |
2904 次 |
最近记录: |