Swift3.0~設置UICollectionView每組(section)的背景

參考原文: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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市损晤,隨后出現(xiàn)的幾起案子软棺,更是在濱河造成了極大的恐慌,老刑警劉巖尤勋,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件喘落,死亡現(xiàn)場離奇詭異,居然都是意外死亡最冰,警方通過查閱死者的電腦和手機瘦棋,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來暖哨,“玉大人赌朋,你說我怎么就攤上這事∑茫” “怎么了沛慢?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長达布。 經(jīng)常有香客問我团甲,道長,這世上最難降的妖魔是什么黍聂? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任躺苦,我火速辦了婚禮,結果婚禮上分冈,老公的妹妹穿的比我還像新娘圾另。我一直安慰自己霸株,他們只是感情好雕沉,可當我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著去件,像睡著了一般坡椒。 火紅的嫁衣襯著肌膚如雪扰路。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天倔叼,我揣著相機與錄音汗唱,去河邊找鬼。 笑死丈攒,一個胖子當著我的面吹牛哩罪,可吹牛的內容都是我干的。 我是一名探鬼主播巡验,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼际插,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了显设?” 一聲冷哼從身側響起框弛,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎捕捂,沒想到半個月后瑟枫,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡指攒,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年慷妙,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片允悦。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡景殷,死狀恐怖,靈堂內的尸體忽然破棺而出澡屡,到底是詐尸還是另有隱情猿挚,我是刑警寧澤侣诺,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布炉菲,位于F島的核電站货裹,受9級特大地震影響桐磁,放射性物質發(fā)生泄漏秋柄。R本人自食惡果不足惜辖试,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一冒黑、第九天 我趴在偏房一處隱蔽的房頂上張望熄攘。 院中可真熱鬧姚淆,春花似錦孕蝉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至搏讶,卻和暖如春佳鳖,著一層夾襖步出監(jiān)牢的瞬間霍殴,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工系吩, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留来庭,地道東北人。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓穿挨,卻偏偏與公主長得像月弛,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子科盛,可洞房花燭夜當晚...
    茶點故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內容