如何在iOS Swift 4中为UITableView的部分设置阴影?

时间:2017-11-05 07:58:17

标签: ios swift uitableview shadow xcode9

我想在iOS Swift的每个部分(单元格组)周围设置阴影。 像这样:
enter image description here

1 个答案:

答案 0 :(得分:0)

通过UICollectionView可以轻松实现,

由子类UICollectionViewFlowLayout DecorationView

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

more code in github