Warm tip: This article is reproduced from stackoverflow.com, please click
swift uitableview uicollectionview uicollectionviewcell uicollectionviewlayout

align single UICollectionViewCell to the left of the collectionView

发布于 2020-03-29 12:46:24

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)
Questioner
WalterBeiter
Viewed
396
K4747Z 2020-02-06 23:58

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