UICollectionView
UICollectionView可以加载的3种可重用视图,都是继承UICollectionReusableView
- 1.Cell,在collectionview中注册
- SupplementaryView,也就是section的headerView和footerView,在collectionview中注册
- DecorationView, 装饰视图,常用于设置section的背景,在UICollectionViewLayout中注册
UICollectionViewLayout
UICollectionViewLayout 用于布局cell,supplementary(header/footer), decorationView 属于抽象类,系统提供2种子类:UICollectionViewFlowLayout,
自定义layout
当系统提供的layout子类不能满足需求时需要自定义Layout
- 使用场景1:为每个section区域添加背景图
//CustomLayout.Swift
override func prepare() {
super.prepare()
//自定义的Layout注册一个装饰视图 CustomDecorationView :UICollectionReusableView
register(CustomDecorationView.self, forDecorationViewOfKind: identifier)
}
//用于返回collectionview可见区域的布局属性数组
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let superAttrs = super.layoutAttributesForElements(in: rect)
var attrs: [UICollectionViewLayoutAttributes] = []
if let superAttrs = superAttrs {
attrs = NSMutableArray(array: superAttrs) as! [UICollectionViewLayoutAttributes]
}
let indexPath = IndexPath(item: 0, section: 0)
//创建可重用的装饰视图DecorationView的attributes
let attr = UICollectionViewLayoutAttributes(forDecorationViewOfKind: identifier, with: indexPath)
//Y原点从每个setion的headview.top开始
attr.frame = CGRect(x: 0, y: 350, width: backgroundViewWidth, height: backgroundViewHeight)
//层级,cell或者supplementary的层级是0
attr.zIndex = -1
//往数组中添加
attrs.append(attr)
return attrs
}
- 使用场景2:瀑布流