iosswiftuicollectionviewuicollectionviewlayoutuicollectionviewdelegate

Adjust insets of a specific section in UICollectionView


  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?


Solution

  • 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;
    
    }