參考原文:http://c0ming.me/different-section-background-color/
最近寫的小項目中脑慧,UICollectionView每一組的背景都是指定的财剖,但是UICollectionView 無法通過屬性設置或數(shù)據(jù)源來為不同的 Section 設置不同的背景顏色蚕甥。好發(fā)愁啊~~~~
幸好我們可以自定義布局地熄,但是我們也不需要做太大的變動夭咬,只需自定義一個繼承于UICollectionViewFlowLayout的YYCollectionViewFlowLayout发魄,我們還是使用系統(tǒng)內置的Flow布局泰偿。
剛開始我就在想,這個Section的背景到底要用到UICollectionView的哪些屬性呢铸豁?后來我查看各種資料灌曙,發(fā)現(xiàn)原來它用到的是 UICollectionView 的 Decoration(裝飾) 視圖 。Decoration 視圖不同與Cell和Supplementary节芥, 它無法通過數(shù)據(jù)源來設置在刺,而是由布局對象來定義和管理。
無論是定義 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 視圖無法通過數(shù)據(jù)源來設置翼抠,也沒有 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 視圖机久;
定義: 在適當?shù)牡胤蕉x 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侠畔,并實現(xiàn)代理方法就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
}
SectionBackgroundColor.png