給UICollectionView的Section設(shè)置背景顏色

UICollectionView沒有設(shè)置Section背景顏色的屬性验懊。需要自定義布局對(duì)象(UICollectionViewLayout)

Section的背景顏色屬于UICollectionView的 Decoration(裝飾)視圖 。
Decoration 視圖無法通過數(shù)據(jù)源來設(shè)置,而是由布局對(duì)象來定義和管理睦优。

無論是定義 Cell 視圖辱匿、Supplementary 視圖還是 Decoration 視圖都是通過它們的 attributes(UICollectionViewLayoutAttributes)來定義的顽分。

1.由于沒有backgroundColor屬性。需要自定義UICollectionViewLayoutAttributes

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

2.Decoration視圖屬于UICollectionReusableView 的子類含友,但Decoration 視圖無法通過數(shù)據(jù)源來設(shè)置,也沒有 dequeue相關(guān)的方法校辩,所以自定義的屬性是通過 UICollectionReusableView 的 apply 方法在 UICollectionView 布局時(shí)生效窘问。

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.添加自定義的布局對(duì)象到Decoration 視圖上

  • 注冊(cè)Decoration 視圖
  • 定義Decoration視圖的布局attributes
  • layoutAttributesForElementsInRect返回 Decoration 視圖的布局 attributes
class FLFoodCategoryCollectionViewFlowLayout: UICollectionViewFlowLayout {
    
    private var decorationViewAttrs: [UICollectionViewLayoutAttributes] = []
    
    override init() {
        super.init()
        
        //注冊(cè)
        self.register(FLFoodCategoryCollectionReusableView.classForCoder(), forDecorationViewOfKind: "SectionBackground")

    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func prepare() {
        super.prepare()
        
        //Section個(gè)數(shù)
        guard let numberOfSections = self.collectionView?.numberOfSections,
            let delegate = self.collectionView?.delegate as? FLFoodCategoryCollectionViewDelegateFlowLayout
            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 = 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
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末惠赫,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子故黑,更是在濱河造成了極大的恐慌儿咱,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,681評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件场晶,死亡現(xiàn)場(chǎng)離奇詭異概疆,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)峰搪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門岔冀,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事使套」藓簦” “怎么了?”我有些...
    開封第一講書人閱讀 169,421評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵侦高,是天一觀的道長(zhǎng)嫉柴。 經(jīng)常有香客問我,道長(zhǎng)奉呛,這世上最難降的妖魔是什么计螺? 我笑而不...
    開封第一講書人閱讀 60,114評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮瞧壮,結(jié)果婚禮上登馒,老公的妹妹穿的比我還像新娘。我一直安慰自己咆槽,他們只是感情好陈轿,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,116評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著秦忿,像睡著了一般麦射。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上灯谣,一...
    開封第一講書人閱讀 52,713評(píng)論 1 312
  • 那天潜秋,我揣著相機(jī)與錄音,去河邊找鬼胎许。 笑死半等,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的呐萨。 我是一名探鬼主播杀饵,決...
    沈念sama閱讀 41,170評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼谬擦!你這毒婦竟也來了切距?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,116評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤惨远,失蹤者是張志新(化名)和其女友劉穎谜悟,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體北秽,經(jīng)...
    沈念sama閱讀 46,651評(píng)論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡葡幸,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,714評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了贺氓。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蔚叨。...
    茶點(diǎn)故事閱讀 40,865評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出蔑水,到底是詐尸還是另有隱情邢锯,我是刑警寧澤,帶...
    沈念sama閱讀 36,527評(píng)論 5 351
  • 正文 年R本政府宣布搀别,位于F島的核電站丹擎,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏歇父。R本人自食惡果不足惜蒂培,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,211評(píng)論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望榜苫。 院中可真熱鬧护戳,春花似錦、人聲如沸单刁。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽羔飞。三九已至,卻和暖如春檐春,著一層夾襖步出監(jiān)牢的瞬間逻淌,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工疟暖, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留卡儒,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,299評(píng)論 3 379
  • 正文 我出身青樓俐巴,卻偏偏與公主長(zhǎng)得像骨望,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子欣舵,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,870評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容