我有一个像这样的 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)
}
}
当我运行应用程序时,它看起来像这样:
我的问题是,如何使单元格居中?我注意到我可以调整单元格之间的间距,但是如何在红色单元格的左侧添加间距?对此的任何指示将不胜感激。谢谢!
最佳答案
试试这个委托(delegate)函数会有帮助,你需要根据你的需要设置单元格的宽度
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionat section: Int) -> CGFloat {
return 0
}
希望对你有帮助
关于ios - 用于分页 UICollectionView 的居中单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43337624/