UICollectionView 无法通过属性设置或数据源来为不同的 Section 设置不同的背景颜色,要想达到这样的效果就需要自定义自己的布局对象(UICollectionViewLayout)。自定义布局可以完全自定义布局,但这里我们只继承 UICollectionViewFlowLayout 还是使用系统内置的 Flow 布局。
那么 Section 的背景颜色是属于 UICollectionView 的那一块呢?它既不是 Cell 视图,也不是 Supplementary 视图,而是 UICollectionView 的 Decoration(装饰) 视图 。Decoration 视图不同与前两者, 它无法通过数据源来设置,而是由布局对象来定义和管理。
无论是定义 Cell 视图、Supplementary 视图还是 Decoration 视图都是通过它们的 attributes(UICollectionViewLayoutAttributes)来定义的。CollectionView 通过这些 布局相关的属性 来对它们进行布局。来看看 UICollectionViewLayoutAttributes 有那些布局属性:
public var frame: CGRect public var center: CGPoint public var size: CGSize public var transform3D: CATransform3D public var bounds: CGRect public var transform: CGAffineTransform public var alpha: CGFloat public var zIndex: Int // default is 0 public var isHidden: Bool
没有我们需要的背景颜色属性,没关系,我们定义一个 UICollectionViewLayoutAttributes 子类,在这个子类里定义 backgroundColor 属性:
class SBCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes {  
    var backgroundColor = UIColor.clear
} 
 注意所定义的属性类型要满足 NSCopying 协议。
Cell 视图、Supplementary 视图它们都是 UICollectionReusableView 的子类,Decoration 视图也不例外。但前面已说到 Decoration 视图无法通过数据源来设置,也没有 dequeue 相关的方法,自定义的属性只能通过 UICollectionReusableView 的 apply 方法在 CollectionView 布局时来使之生效。
class SBCollectionReusableView: UICollectionReusableView {
    override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
        super.apply(layoutAttributes)
        guard let attr = layoutAttributes as? SBCollectionViewLayoutAttributes else {
            return
        }
        self.backgroundColor = attr.backgroundColor
    }
} 
 说到这里 Decoration 视图是怎样添加到自定义的布局对象的呢? 其实和 Cell 视图、Supplementary 视图一样 ,添加 Decoration 视图到布局对象的流程:
class SBCollectionViewFlowLayout: UICollectionViewFlowLayout {
    private var decorationViewAttrs: [UICollectionViewLayoutAttributes] = []
    override func prepare() {
        super.prepare()
        guard let numberOfSections = self.collectionView?.numberOfSections,
            let delegate = self.collectionView?.delegate as? SBCollectionViewDelegateFlowLayout
            else {
            return
        }
        // 1、注册
        self.register(SBCollectionReusableView.classForCoder(), forDecorationViewOfKind: SectionBackground)
        self.decorationViewAttrs.removeAll()
        for section in 0..<numberOfSections {
            guard let numberOfItems = self.collectionView?.numberOfItems(inSection: section),
                numberOfItems > 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 -= sectionInset.left
            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 = SBCollectionViewLayoutAttributes(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)
        for attr in self.decorationViewAttrs {
            if rect.intersects(attr.frame) {
                // 3、返回
                attrs?.append(attr)
            }
        }
        return attrs
    }
} 
 最后我们为 Decoration 视图增加协议方法,使它也可以“通过”数据源来设置。
protocol SBCollectionViewDelegateFlowLayout: UICollectionViewDelegateFlowLayout {  
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor
}
extension SBCollectionViewDelegateFlowLayout {  
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor {
        return UIColor.clear
    }
} 
  
 
完整 Demo: https://github.com/c0ming/SBCollectionViewFlowLayout
参考: Including Decoration Views in Your Custom Layouts