ios - 用于分页 UICollectionView 的居中单元格

标签 ios swift uicollectionview

我有一个像这样的 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)
}

还有我的代表们:

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)
    }

}

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

enter image description here

我的问题是,如何使单元格居中?我注意到我可以调整单元格之间的间距,但是如何在红色单元格的左侧添加间距?对此的任何指示将不胜感激。谢谢!

最佳答案

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

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

希望对你有帮助

关于ios - 用于分页 UICollectionView 的居中单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43337624/

相关文章:

ios - 我的一个 UICollectionViews 没有滚动或响应我的 UIScrollView 容器内的触摸事件 [Puzzling]

ios - 减小 UIImage 大小不起作用

ios - swift 。 Viewcontroller 知道子类

json - ObjectMapper 在 Swift 中返回 NIL

swift - 是否可以让通话状态栏覆盖内容而不是将所有内容都向下移动?

ios - 在 Swift 的 iOS 应用程序中显示表格(在 html/Excel 电子表格中的意思)

ios - 单击 UICollectionViewCell 时如何转换到新 Controller (以编程方式)

ios - fb ios sdk 4.8 同时分享图片和url

ios - ScrollsToTop 功能在 iOS9 中无法正常工作

ios - 将 textView 设置为从顶部开始(Swift)