给UICollectionView的Section设置背景颜色

UICollectionView没有设置Section背景颜色的属性。需要自定义布局对象(UICollectionViewLayout)

Section的背景颜色属于UICollectionView的 Decoration(装饰)视图 。
Decoration 视图无法通过数据源来设置,而是由布局对象来定义和管理。

无论是定义 Cell 视图、Supplementary 视图还是 Decoration 视图都是通过它们的 attributes(UICollectionViewLayoutAttributes)来定义的。

1.由于没有backgroundColor属性。需要自定义UICollectionViewLayoutAttributes

private class FLFoodCategoryCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes {
    var backgroundColor = UIColor.clear
}

2.Decoration视图属于UICollectionReusableView 的子类,但Decoration 视图无法通过数据源来设置,也没有 dequeue相关的方法,所以自定义的属性是通过 UICollectionReusableView 的 apply 方法在 UICollectionView 布局时生效。

private class FLFoodCategoryCollectionReusableView: UICollectionReusableView {
    
    private override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
        super.apply(layoutAttributes)
        guard let attr =  layoutAttributes as? FLFoodCategoryCollectionViewLayoutAttributes  else {
            return
        }
        self.backgroundColor = attr.backgroundColor
    }
}

3.添加自定义的布局对象到Decoration 视图上

  • 注册Decoration 视图
  • 定义Decoration视图的布局attributes
  • layoutAttributesForElementsInRect返回 Decoration 视图的布局 attributes
class FLFoodCategoryCollectionViewFlowLayout: UICollectionViewFlowLayout {
    
    private var decorationViewAttrs: [UICollectionViewLayoutAttributes] = []
    
    override init() {
        super.init()
        
        //注册
        self.register(FLFoodCategoryCollectionReusableView.classForCoder(), forDecorationViewOfKind: "SectionBackground")

    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func prepare() {
        super.prepare()
        
        //Section个数
        guard let numberOfSections = self.collectionView?.numberOfSections,
            let delegate = self.collectionView?.delegate as? FLFoodCategoryCollectionViewDelegateFlowLayout
            else {
                return
        }
        
        self.decorationViewAttrs.removeAll()
        for section in 0.. 0,
                let firstItem = self.layoutAttributesForItem(at: IndexPath(item: 0, section: section)),
                let lastItem = self.layoutAttributesForItem(at: IndexPath(item: numberOfItems - 1, section: section)) else {
                    continue
            }
            
            var sectionInset = self.sectionInset
            if let inset = delegate.collectionView?(self.collectionView!, layout: self, insetForSectionAt: section) {
                sectionInset = inset
            }
            
            var sectionFrame = firstItem.frame.union(lastItem.frame)
            sectionFrame.origin.x = 0
            sectionFrame.origin.y -= sectionInset.top
            
            if self.scrollDirection == .horizontal {
                sectionFrame.size.width += sectionInset.left + sectionInset.right
                sectionFrame.size.height = self.collectionView!.frame.height
            } else {
                sectionFrame.size.width = self.collectionView!.frame.width
                sectionFrame.size.height += sectionInset.top + sectionInset.bottom
            }
            
            // 2、定义视图属性
            let attr = FLFoodCategoryCollectionViewLayoutAttributes(forDecorationViewOfKind: "SectionBackground", with: IndexPath(item: 0, section: section))
            attr.frame = sectionFrame
            attr.zIndex = -1
            attr.backgroundColor = delegate.collectionView(self.collectionView!, layout: self, backgroundColorForSectionAt: section)
            self.decorationViewAttrs.append(attr)
        }
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var attrs = super.layoutAttributesForElements(in: rect)
        attrs?.append(contentsOf: self.decorationViewAttrs.filter {
            return rect.intersects($0.frame)
        })
        return attrs // 3、返回
    }

    
}

4.为视图布局增加修改颜色的属性方法

protocol FLFoodCategoryCollectionViewDelegateFlowLayout: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor
}

你可能感兴趣的:(给UICollectionView的Section设置背景颜色)