Adjust insets of a specific section in UICollectionView
Asked Answered
C

3

7
  1. insetForSectionAtIndex (on DelegateFlowLayout) enables one to set insets for all cells within a section

  2. sectionInset (on FlowLayout) enables one to set insets that applies to all sections.

However, I am looking for a way of applying insets to only one specific section - is this possible?

Carmon answered 9/8, 2016 at 18:38 Comment(0)
M
9

You must have to implement UICollectionViewDelegateFlowLayout to your class with this method:

For Swift 4, 5+

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

    var edgeInsets = UIEdgeInsets()
    if section == THE_SECTION_YOU_WANT {
        // edgeInsets configuration stuff
    }

    return edgeInsets;
}

For Swift 3

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

    var edgeInsets = UIEdgeInsets()
    if section == THE_SECTION_YOU_WANT {
        // edgeInsets configuration stuff
    }

    return edgeInsets;

}
Mutt answered 9/8, 2016 at 20:1 Comment(6)
I tried this earlier, and it seems to apply the inset to all elements in the section. Is there a way I can apply it to the entire section, not each element?Carmon
@GauravSharma This method apply the inset to the entire section, that's the reason it gives it an section Int.Mutt
just tried again - same result - it applies the insets to each cell in the section, rather than the section.Carmon
@GauravSharma and what is the difference? Do you want to apply the inset to the header section and footer section?Mutt
Nope, I want to inset the entire section (not each item in the section).Carmon
Actually that works fine - there was something else that made it look like it was not working. Putting a 100 pixel left/right inset works fine - if anyone else tries this and gets odd results, bear in mind the collection view applies automatic spacing which may make it look like inner cells are being inset!Carmon
B
1

for swift 4 is named:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
...
Bridegroom answered 11/4, 2018 at 14:5 Comment(0)
P
1

You'd do something like this from the UICollectionViewDelegateFlowLayout protocol:

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

        switch section {
        case 0:
            return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        case 1:
            return UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
        }
    }
Prasad answered 18/6, 2020 at 19:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.