Search code examples
swiftuitableviewuicollectionviewuicollectionviewcelluicollectionviewlayout

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)

Solution

  • 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