0

My question for today that I have been trying to figure out for a while but what is really buggy or doesn't work because I'm unclear on how to implement it is how to change the color of the individual sections in a collection view. For example, I would like sections 0-2 to be orange, 3-5 to be blue, 6-8 to be pink, and 9-11 to be green.

I have tried to implement the code in these two repositories. The first one after implementing worked somewhat but is very buggy when I try to scroll the collection view, but I think I didn't implement it correctly. The second one after trying to implement it, nothing showed up so I don't think I did that correctly either. My goal is to hard-set the color for each section.

Here is the code for creating the collection view:

let friendsCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        //also tried let layout = SectionBackgroundFlowLayout() and let layout = ColorFlowLayout()
        layout.scrollDirection = .horizontal
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.translatesAutoresizingMaskIntoConstraints = false
        cv.register(FriendsCell.self, forCellWithReuseIdentifier: "cell")
        cv.layer.cornerRadius = 10
        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        return cv
       }()

This is an addition that I pulled from the example repo of the second repo:

class ColorFlowLayout: UICollectionViewFlowLayout {

// MARK: prepareLayout

override func prepare() {
    super.prepare()

//        minimumLineSpacing = 8.0
//        minimumInteritemSpacing = 8.0
//        sectionInset = UIEdgeInsetsMake(8, 8, 8, 8)
//
//        let width = (UIScreen.main.bounds.width / 3) - 2 * 8.0
//        itemSize = CGSizeMake(width, 100)

    //register(SCSBCollectionReusableView.self, forDecorationViewOfKind: "sectionBackground")

    register(UICollectionView.self, forDecorationViewOfKind: "sectionBackground")
}

// MARK: layoutAttributesForElementsInRect
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    let attributes = super.layoutAttributesForElements(in: rect)
    var allAttributes = [UICollectionViewLayoutAttributes]()

    if let attributes = attributes {

        for attr in attributes {
            // Look for the first item in a row
            // You can also calculate it by item (remove the second check in the if below and change the tmpWidth and frame origin
            if (attr.representedElementCategory == UICollectionElementCategory.cell && attr.frame.origin.x == self.sectionInset.left) {

                // Create decoration attributes
                let decorationAttributes = SCSBCollectionViewLayoutAttributes(forDecorationViewOfKind: "sectionBackground", with: attr.indexPath)
                // Set the color(s)
                if (attr.indexPath.section % 2 == 0) {
                    decorationAttributes.color = UIColor.orange //Just two different colors to test at the moment
                } else {
                    decorationAttributes.color = UIColor.blue
                }

                // Make the decoration view span the entire row
                let tmpWidth = self.collectionView!.contentSize.width
                let tmpHeight = self.collectionView!.contentSize.height // or attributes.frame.size.height instead of itemSize.height if dynamic or recalculated


                decorationAttributes.frame = CGRect(x: 0, y: attr.frame.origin.y - self.sectionInset.top, width: tmpWidth, height: tmpHeight)

                // Set the zIndex to be behind the item
                decorationAttributes.zIndex = attr.zIndex - 1

                // Add the attribute to the list
                allAttributes.append(decorationAttributes)
            }
        }
        // Combine the items and decorations arrays
        allAttributes.append(contentsOf: attributes)
    }

    return allAttributes
}

}

Let me know if you have any questions or if I could provide any more information. All help is much appreciated!

Keshu R.
  • 5,045
  • 1
  • 18
  • 38
Jaqueline
  • 465
  • 2
  • 8
  • 25
  • You would need to implement a decoration view behind the section. In iOS 13 with the new compositional layout this is trivial. If you don’t need iOS 12 support you should abandon flow layout entirely. – matt Dec 11 '19 at 05:04
  • I need the iOS 12 support. Would you be able to provide an example in code. I’ve tried but can’t get it to work with my project. – Jaqueline Dec 11 '19 at 05:12
  • Well, I’ve explained elsewhere how make a decoration view for a layout subclass. But it isn’t simple. – matt Dec 11 '19 at 05:18
  • Could you please provide me with a link or example of this perhaps from what you have already done? My problem is how to tie it all together. – Jaqueline Dec 11 '19 at 06:48
  • This is my essay on how to make a decoration view: https://stackoverflow.com/a/39218108/341994 But it's all pretty horrendous as you'll see. – matt Dec 11 '19 at 07:03
  • Is it possible to try to connect and work on what I’ve already tried to do so that it’s a little easier? – Jaqueline Dec 11 '19 at 15:00
  • @matt I've had more time to read through your post and it makes more sense. Where my confusion is I'm not sure how all of it connects to the CollectionView when I create it am I supposed to add the viewForSupplementaryElementOfKind and how do I do that since it's not a header view – Jaqueline Dec 12 '19 at 15:29

0 Answers0