How to change the background section

38 views Asked by At

I have a collection view and I want to add a image to the background but I want that the imagen change depending the section.

I`m changing the header and I can modify the header depending the section but I can“t make the same with the background of the section.

This is my background decoration:

class SectionBackground: UICollectionReusableView {
    
    let imageView = UIImageView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)

        
        configure()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension SectionBackground {
    func configure() {
        
        imageView.image = UIImage(named: "categorias_cat_1_base")
        
        imageView.frame = self.bounds
        
        addSubview(imageView)

    }
}

I`m using the method 'viewForSupplementaryElementOfKind' but i can`t use it for the background I tried to check the kind but there isn`t any kind for the section background.

1

There are 1 answers

0
deniz On

Since you tagged uicollectionviewcompositionallayout in your question, I am presuming that's the layout you are using. Adding a background to a section is fairly straightforward.

  1. Define an ElementKind struct in your code

     struct ElementKind {
         static let background = "background-element-kind"
         //other element kinds such as header and footer kinds can be added here as well
     }
    
  2. While you are configuring your compositional layout for the collection view in question, insert this sample code in the appropriate place.

     let sectionBackground = NSCollectionLayoutDecorationItem.background(elementKind: ElementKind.background)
     section.decorationItems = [sectionBackground]
    
  3. Lastly, when you are finished with configuring the UICollectionViewCompositionalLayout, you have to register the decoration view with the layout. You need to do something like this:

     let myCustomLayout = UICollectionViewCompositionalLayout(section: section) //or whichever initializer you are using 
     myCustomLayout.register(SectionBackground.self, forDecorationViewOfKind: ElementKind.background)
     return myCustomLayout
    

Cheers!