SwiftUI 中 UICollectionView 横向滑动分页技巧

UICollectionView 在 iOS 开发中很常见,尤其适合展示大量数据。但有时我们需要实现横向分页,比如每页固定显示 16 个数据,即使实际数据不足。

一种解决方法是添加虚拟数据凑足页数,但比较麻烦。更推荐的做法是自定义 UICollectionViewFlowLayout,重写 collectionViewContentSize 方法。

我们可以通过计算屏幕宽度和数据个数,得到新的 contentSize。代码示例:

override var collectionViewContentSize: CGSize {
    let size: CGSize = super.collectionViewContentSize
    let collectionViewWidth: CGFloat = self.collectionView!.frame.size.width
    let nbOfScreen: Int = Int(ceil(size.width / collectionViewWidth))
    let newSize: CGSize = CGSize(width: collectionViewWidth * CGFloat(nbOfScreen), height: size.height)
    return newSize
}

这里用 ceil 函数向上取整,确保每页都完整显示。

pdf 文件大小:153.48KB