18

I've got a collectionView that is inside a tableView cell. The collectionView has multiple sections. If a section has only one cell, the cell appears centered. How can I align that single cell to the left?

collectionView inside tableView cell

The collectionView has the following flowLayout:

let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
flowLayout.minimumInteritemSpacing = 0
flowLayout.minimumLineSpacing = 0
flowLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
collectionView.setCollectionViewLayout(flowLayout, animated: true)
WalterBeiter
  • 2,021
  • 3
  • 23
  • 48
  • 1
    Have you looked into this: https://stackoverflow.com/questions/22539979/left-align-cells-in-uicollectionview – rs7 Feb 04 '20 at 05:22
  • Well all answers from that link move all collectionViewCells to the left, so all cells from all sections. I only want that behavior for that section that only has one cell. – WalterBeiter Feb 05 '20 at 10:48
  • 1
    You can add one more ghost cell when you have only one cell in a section and hide it, then the first cell will be left-aligned. – Mohan Meruva Feb 05 '20 at 11:01

2 Answers2

21

Since sectionInset is the same as func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { } protocol, one could call this protocol to know which section has only one cell left.

You can replace :

flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

With:

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {

    if collectionView.numberOfItems(inSection: section) == 1 {

         let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout

        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: collectionView.frame.width - flowLayout.itemSize.width)

    }

    return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)

}

This red cell is the only one left in the second section , and it is left aligned:

enter image description here

Celeste
  • 1,519
  • 6
  • 19
9

I had same issue. My solution is to change of collectionView's estimate size.

Automatic -> None

enter image description here

Seokmin Jeong
  • 119
  • 1
  • 4