0

我正在尝试使用新的 UICollectionViewCompositionalLayout 在 iMessage 中复制 Stickers 应用程序。

但是,我似乎无法重现水平“分页”行为。

应该有n + 1部分,其中n我的页数,水平对齐。

期望的行为:

在此处输入图像描述

我想出了什么:

在此处输入图像描述

我的代码:

@available(iOS 13.0, *)
class TestViewController: UIViewController, UICollectionViewDataSource {

    @IBOutlet weak var collection: UICollectionView!


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 4
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)

        cell.backgroundColor = UIColor(hue: CGFloat(drand48()), saturation: 1, brightness: 1, alpha: 1)

        return cell
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        collection.dataSource = self
        collection.collectionViewLayout = createLayout()
    }


    func createLayout() -> UICollectionViewLayout {
        let layout = UICollectionViewCompositionalLayout { (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in

            if sectionIndex == 0 {

                let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(49), heightDimension: .absolute(49))
                let item = NSCollectionLayoutItem(layoutSize: itemSize)

                let groupSize = NSCollectionLayoutSize(widthDimension: .absolute(49), heightDimension: .absolute(49))
                let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])

                let section = NSCollectionLayoutSection(group: group)
                section.orthogonalScrollingBehavior = .continuous
                section.contentInsets.leading = 16
                section.contentInsets.trailing = 16

                section.interGroupSpacing = 8

                return section
            } else {
                let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(0.2), heightDimension: .fractionalHeight(1.0))
                let item = NSCollectionLayoutItem(layoutSize: itemSize)

                let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalWidth(0.2))
                let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])

                let section = NSCollectionLayoutSection(group: group)

                return section
            }
        }
        return layout
    }
}
4

0 回答 0