I\'m building a mosaic view using UICollectionView
.
I have subclassed UICollectionViewFlowLayout
to layout a fixed grid that can be scrolle
To implement custom section background in CollectionView in Swift 5,
class CustomFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes = super.layoutAttributesForElements(in: rect)
for section in 0.. UICollectionViewLayoutAttributes? {
let attrs = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath)
if elementKind == "background"{
attrs.size = collectionView!.contentSize
//calculate frame here
let items = collectionView!.numberOfItems(inSection: indexPath.section)
let totalSectionHeight:CGFloat = CGFloat(items * 200)
let cellAttr = collectionView!.layoutAttributesForItem(at: indexPath)
attrs.frame = CGRect(x: 0, y: cellAttr!.frame.origin.y, width: collectionView!.frame.size.width, height: totalSectionHeight)
attrs.zIndex = -10
return attrs
}else{
return super.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath)
}
}
}
In your CollectionView DataSource,
override func viewDidLoad() {
super.viewDidLoad()
//register collection view here
...
//setup flow layout & register supplementary view
let customFlowLayout = CustomFlowLayout()
collectionView.collectionViewLayout = customFlowLayout
collectionView.register(UINib(nibName: "BackgroundReusableView", bundle: nil), forSupplementaryViewOfKind: "background", withReuseIdentifier: "BackgroundReusableView")
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == "background"{
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "BackgroundReusableView", for: indexPath) as! BackgroundReusableView
return view
}
return UICollectionReusableView()
}