参考原文:http://c0ming.me/different-section-background-color/
最近写的小项目中,UICollectionView每一组的背景都是指定的,但是UICollectionView 无法通过属性设置或数据源来为不同的 Section 设置不同的背景颜色。好发愁啊~~~~
幸好我们可以自定义布局,但是我们也不需要做太大的变动,只需自定义一个继承于UICollectionViewFlowLayout的YYCollectionViewFlowLayout,我们还是使用系统内置的Flow布局。
刚开始我就在想,这个Section的背景到底要用到UICollectionView的哪些属性呢?后来我查看各种资料,发现原来它用到的是 UICollectionView 的 Decoration(装饰) 视图 。Decoration 视图不同与Cell和Supplementary, 它无法通过数据源来设置,而是由布局对象来定义和管理。
无论是定义 Cell 视图、Supplementary 视图还是 Decoration 视图都是通过它们的 attributes(UICollectionViewLayoutAttributes)来定义的。CollectionView 通过这些 布局相关的属性 来对它们进行布局。来看看 UICollectionViewLayoutAttributes 有那些布局属性:
open var frame: CGRect
open var center: CGPoint
open var size: CGSize
open var transform3D: CATransform3D
@available(iOS 7.0, *)
open var bounds: CGRect
@available(iOS 7.0, *)
open var transform: CGAffineTransform
open var alpha: CGFloat
open var zIndex: Int // default is 0
open var isHidden: Bool // As an optimization, UICollectionView might not create a view for items whose hidden attribute is YES
open var indexPath: IndexPath
蓝瘦香菇没有我们想要的颜色属性,那我们就先来定义一个继承于UICollectionViewLayoutAttributes 的子类,然后自己定义一个backgroundColor属性吧:
class YYCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes {
var backgroundColor = UIColor.clear
}
Cell 视图、Supplementary 视图它们都是 UICollectionReusableView 的子类,Decoration 视图也不例外。但前面已说到 Decoration 视图无法通过数据源来设置,也没有 dequeue 相关的方法,自定义的属性只能通过 UICollectionReusableView 的 apply 方法在 CollectionView 布局时来使之生效。
class YYCollectionReusableView: UICollectionReusableView {
override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) {
super.apply(layoutAttributes)
guard let attr = layoutAttributes as? YYCollectionViewLayoutAttributes else {
return
}
self.backgroundColor = attr.backgroundColor
}
}
注册>定义>返回
注册: 布局对象注册 Decoration 视图;
定义: 在适当的地方定义 Decoration 视图的布局 attributes;
-
返回: 在布局对象的 layoutAttributesForElementsInRect 方法返回 Decoration 视图的布局 attributes。
class YYCollectionViewFlowLayout: UICollectionViewFlowLayout { private var decorationViewAttrs: [UICollectionViewLayoutAttributes] = [] // MARK: - Init override init() { super.init() setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() setup() } // MARK: - Setup func setup() { // 1、注册 self.register(YYCollectionReusableView.classForCoder(), forDecorationViewOfKind: SectionBackground) } override func prepare() { super.prepare() guard let numberOfSections = self.collectionView?.numberOfSections, let delegate = self.collectionView?.delegate as? YYCollectionViewDelegateFlowLayout else { return } 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 = 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 = YYCollectionViewLayoutAttributes(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、返回 } }
添加代理:
protocol YYCollectionViewDelegateFlowLayout: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor
}
extension YYCollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor {
return UIColor.clear
}
}
最后,我们在Controller中遵循YYCollectionViewDelegateFlowLayout,并实现代理方法就OK啦
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, backgroundColorForSectionAt section: Int) -> UIColor {
if section == 0 {
return UIColor.red
} else if section == 1 {
return UIColor.yellow
} else if section == 2 {
return UIColor.brown.withAlphaComponent(0.8)
}
return UIColor.blue
}