0

I have a collection view with 3 sections, the first two sections work fine with UICollectionViewFlowLayout but the 3rd one needs a custom implementation.

I understand that a collection view can only have one layout, so I've been trying to only perform work in the overriden prepare function if I'm in the right section. This is where it tends to fall apart, I can't work out a straightforward way to figure out which section the cell is in which I'm calculating layout attributes for.

Not sure if there's a better approach than conditionally performing calculations in the prepare function either.

A point in the right direction would be great!

mike
  • 2,073
  • 4
  • 20
  • 31

1 Answers1

0

I think this is a good approach:

1- Create your custom section with its own .xib file

class CustomSection: UICollectionReusableView {

    override func awakeFromNib() {
        super.awakeFromNib()
    }
}

2- Implement the UICollectionViewDelegateFlowLayout delegate method

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        // In case its a section header (UICollectionElementKindSectionFooter for footer)
        if kind == UICollectionElementKindSectionHeader {

            // This will be the section number

            let section = indexPath.section

            if section == 3 {

                let customSection = collectionView.dequeueReusableSupplementaryView(ofKind: kind,withReuseIdentifier: "CustomSection", for: indexPath) as! CustomSection
                return customSection

            }
            else {

               //TODO: Return your default section

            }

        }
}

3- Don't forget to register the section with your UICollectionView

let customSectionNib = UINib.init(nibName: "CustomSection", bundle: nil)
        collectionView.register(customSectionNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CustomSection")
omar
  • 251
  • 3
  • 12