How to add a background image to UICollectionView that will scroll and zoom will cells

后端 未结 2 1905
独厮守ぢ
独厮守ぢ 2021-01-02 20:24

I\'m building a mosaic view using UICollectionView.

I have subclassed UICollectionViewFlowLayout to layout a fixed grid that can be scrolle

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 21:07

    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()
            }
    

提交回复
热议问题