Swift_LearnSwift编程ios-UI

Swift3.0~设置UICollectionView每组(se

2016-12-01  本文已影响388人  大脸猫121

参考原文: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
    }
 }
注册>定义>返回

添加代理:

 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
}
SectionBackgroundColor.png
上一篇 下一篇

猜你喜欢

热点阅读