用于分页UICollectionView的居中单元格

Kex*_*Ari 8 ios uicollectionview swift

我有一个像这样的UICollectionView设置:

viewDidLoad:

func setupCollectionView() {
  collectionView.delegate = self
  collectionView.dataSource = self
  collectionView.register(UINib(nibName: "NewQuizzesCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "NewQuizzesCollectionViewCell")

  let flowLayout = UICollectionViewFlowLayout()
  flowLayout.scrollDirection = .horizontal
  flowLayout.minimumInteritemSpacing = 20
  flowLayout.minimumLineSpacing = 20
  collectionView.isPagingEnabled = true
  collectionView.setCollectionViewLayout(flowLayout, animated: false)
}
Run Code Online (Sandbox Code Playgroud)

我的代表们:

extension NewQuizzesViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

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

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: NewQuizzesCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewQuizzesCollectionViewCell", for: indexPath) as! NewQuizzesCollectionViewCell
        cell.backgroundColor = colors[indexPath.row]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.frame.size.width*0.8, height: collectionView.frame.size.height*0.8)
    }

}
Run Code Online (Sandbox Code Playgroud)

当我运行应用程序时,它看起来像这样:

在此输入图像描述

我的问题是,我怎样才能使细胞居中?我注意到我可以调整单元格之间的间距,但是如何在红色单元格的左边添加间距?对此的任何指示都将非常感激.谢谢!

Jog*_*Com 2

尝试这个委托函数会有帮助,您需要根据需要设置单元格的宽度

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionat section: Int) -> CGFloat {
    return 0
}
Run Code Online (Sandbox Code Playgroud)

希望它能帮助你