Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering cells for paging UICollectionView

I have a UICollectionView setup like so:

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

And my delegates:

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

}

When I run the app it looks like this:

enter image description here

My question is, how can I make the cells centered? I noticed I can adjust the spacing between the cells, but how would I add spacing to the left of the red cell? Any pointers on this would be really appreciated. Thanks!

like image 363
KexAri Avatar asked Apr 11 '17 05:04

KexAri


1 Answers

Try this delegate function will help and you need to set width of cell according to you wants

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

Hope it will help you

like image 182
Jogendra.Com Avatar answered Nov 04 '22 09:11

Jogendra.Com