0

I'm trying to create a left aligned collection view. The most poplar way of achieving this seems to be by using Custom Collection view layouts (ex: https://stackoverflow.com/a/36016798/11515703). However, I'm trying to do this without using Custom Layout, because it removes the collection view section headers I've got setup. Is this possible?

I tried doing this like this:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let inset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: view.frame.width)
        
        return inset
    }

The above code achieves the result but it leads to a lot of issues as it conflicts with the collection view flow layout rules. Is there an alternative method ?

This is the result I'm trying to achieve: enter image description here

Note: I'm using collection view cells with variable width.

unknown
  • 788
  • 9
  • 24

2 Answers2

0

contentInset, the custom distance that the content view is inset from the safe area or scroll view edges, Apple documentation

collectionView.contentInset = UIEdgeInsets(
    top: 0,
    left: 16,
    bottom: 0,
    right: 16)
Without contentInset With contentInset
tphduy
  • 119
  • 7
0

You could use contentInset

By default, UIKit automatically adjusts the content inset to account for overlapping bars. You use this property to extend that distance even further, perhaps to accommodate your own custom content.

Read in apple docs

  • Tried this and it doesn't work as ```contentInset``` would be the same for all the cells and I'm using cells with variable width. – unknown May 24 '21 at 05:22