簡體   English   中英

如何在 iOS Swift 4 中為 UITableView 的部分設置陰影?

[英]How to set drop shadow around a section for UITableView in iOS Swift 4?

我想在 iOS Swift 中的每個部分(單元格組)周圍設置陰影。 像這樣:
在此處輸入圖片說明

使用UICollectionView輕松實現這UICollectionView

通過子類UICollectionViewFlowLayoutDecorationView

UITableViewCell變成UICollectionViewCell

使用裝飾視圖實現剖面部分的陰影


class DecorationFlow: UICollectionViewFlowLayout {
    
    private var cache = [IndexPath: UICollectionViewLayoutAttributes]()
    
    override func prepare() {
        super.prepare()
        register(HistoDecorationV.self, forDecorationViewOfKind: HistoDecorationV.id)
        let originX: CGFloat = 15
        let widH: CGFloat = UI.std.width - originX * 2
        guard let collect = collectionView else{
            return
        }
        let sections = collect.numberOfSections
        var originY: CGFloat = 0
        for sect in 0..<sections{
            let sectionFirst = IndexPath(item: 0, section: sect)
            let attributes = UICollectionViewLayoutAttributes(forDecorationViewOfKind: HistoDecorationV.id, with: sectionFirst)
            let itemCount = collect.numberOfItems(inSection: sect)
            originY = originY + 80
            let h: CGFloat = 50 * CGFloat(itemCount)
            attributes.frame = CGRect(x: originX, y: originY, width: widH, height: h)
            originY = originY + h + 15
            cache[sectionFirst] = attributes
        }
    }
    
    
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    
    private func prepareCache() {
      cache.removeAll(keepingCapacity: true)
      cache = [IndexPath: UICollectionViewLayoutAttributes]()
    }
    
    
    override func layoutAttributesForDecorationView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        
        return cache[indexPath]
        
    }

    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var array = super.layoutAttributesForElements(in: rect)
        guard let collection = collectionView, collection.numberOfSections > 0 else{
            return array
        }
        var z = 0
        array?.forEach({
            $0.zIndex = z + 100
            z += 1
        })
        z = 0
        for (_, attributes) in cache {
            
            if attributes.frame.intersects(rect){
                attributes.zIndex = z + 10
                array?.append(attributes)
            }
            z += 1
        }
        return array
    }
}

github 中的更多代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM