Chris
Chris

Reputation: 282

Center First UICollectionViewCell in UICollectionView

I have a UICollectionView that can either have a single cell or two cells.

Is it possible for me to horizontally center the first cell and on panLeft have the second cell centered likewise - to the UICollectionView whose width sizes itself to the screen/view size and cell's proportionally adjusting as well?

From the references I've seen, I believe I need to use the UICollectionViewDelegateFlowLayout insetForSectionAt method, but I'm not able to get it exactly centered for some reason, and also when it is just one cell, I believe the inset causes the UICollectionView to become scrollable because enough space was created..

Illustration 1st two is an example with 2 cells, last is example with 1 cell

Upvotes: 0

Views: 1334

Answers (1)

Hasti Ranjkesh
Hasti Ranjkesh

Reputation: 671

To make collection view cell center, your controller must confirm UICollectionViewDelegateFlowLayout protocol. Use below code to make cells center:

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

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    let width = collectionView.frame.width
    let margin = width * 0.3
    return UIEdgeInsets(top: 10, left: margin / 2, bottom: 10, right: margin / 2)
}

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

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
   return collectionView.frame.width * 0.3 / 2
}

If you return 1 or 2 in numberOfItemsInSection method, It works fine.

Upvotes: 1

Related Questions