使用 UICollectionViewCompositionalLayout 的垂直全屏分页

Vertical full screen paging using UICollectionViewCompositionalLayout

我正在尝试使用 UICollectionViewCompositionalLayout 创建垂直分页 UICollectionView,类似于 TikTok 滚动其提要的方式。我非常接近实现这种体验,但是,单元格的大小并未按照我期望的方式调整,即全屏宽度和高度。这是我想出的在分页时垂直滚动的布局:

let itemSize = NSCollectionLayoutSize(
    widthDimension: .fractionalWidth(1.0),
    heightDimension: .fractionalHeight(1.0)
)
let layoutItem = NSCollectionLayoutItem(layoutSize: itemSize)

let groupSize = NSCollectionLayoutSize(
    widthDimension: .fractionalWidth(1.0),
    heightDimension: .fractionalHeight(1.0)
)
let layoutGroup = NSCollectionLayoutGroup.vertical(
    layoutSize: groupSize,
    subitems: [layoutItem]
)

let layoutSection = NSCollectionLayoutSection(group: layoutGroup)
layoutSection.orthogonalScrollingBehavior = .groupPaging

let config = UICollectionViewCompositionalLayoutConfiguration()
config.scrollDirection = .horizontal

let layout = UICollectionViewCompositionalLayout(section: layoutSection, configuration: config)
return layout

这是集合视图中单元格的屏幕截图(我为每个单元格使用了随机颜色):

有趣的是,如果我设置 config.scrollDirection = .vertical,单元格的大小会符合我的预期(全屏大小),但它会水平滚动而不是垂直滚动。

只需添加

config.contentInsetsReference = .none