Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

align single UICollectionViewCell to the left of the collectionView

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)
like image 874
WalterBeiter Avatar asked Jan 31 '20 08:01

WalterBeiter


2 Answers

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

Automatic -> None

enter image description here

like image 145
Seokmin Jeong Avatar answered Sep 19 '22 00:09

Seokmin Jeong


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

like image 21
Celeste Avatar answered Sep 21 '22 00:09

Celeste