防止UICollectionViewCell投影投射到其他单元格上

时间:2019-01-22 19:03:18

标签: ios uicollectionview calayer

我希望有人可能对此问题有一个明智的解决方案,因为目前我很沮丧。我有一个collectionView,它的所有单元格都将相当大的阴影投射到它们后面的区域上。问题在于,由于它们之间的距离非常近,因此每个单元格还会在前一个单元格上投射阴影。所有这些单元格的layoutAttributes中都具有相同的zIndex,但是Apple似乎会将具有较高indexPath值的单元格放在较高的zIndex中。是否有防止这些细胞将阴影投射到其他细胞上的好方法?

细胞通过以下方式设置阴影:

    cell.layer.shadowOpacity = 1
    cell.layer.shadowRadius = 54
    cell.layer.shadowOffset = CGSize(width: 0, height: 12)
    cell.layer.shadowColor = UIColor.black.withAlphaComponent(0.5).cgColor

谢谢!

2 个答案:

答案 0 :(得分:0)

设置集合视图图层的阴影属性,而不是在每个单元格上进行设置。确保集合视图没有backgroundView并且其backgroundColor为nil。另外,请确保集合视图的某些祖先视图确实具有背景色或其他填充颜色。

结果:

enter image description here

源代码:

import UIKit

class ViewController: UIViewController, UICollectionViewDataSource {

    var cellIdentifier: String { return "cell" }

    override func loadView() {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
        view.backgroundColor = .white

        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 50, height: 50)
        layout.minimumInteritemSpacing = 4
        layout.minimumLineSpacing = 4
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)

        let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
        collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        collectionView.backgroundColor = nil
        collectionView.dataSource = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)

        collectionView.layer.shadowColor = UIColor.black.cgColor
        collectionView.layer.shadowRadius = 8
        collectionView.layer.shadowOpacity = 1

        view.addSubview(collectionView)

        self.view = view
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath)
        let layer = cell.contentView.layer
        layer.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        layer.borderColor = #colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1)
        layer.borderWidth = 2
        layer.cornerRadius = 8
        layer.masksToBounds = true
        return cell
    }

}

答案 1 :(得分:0)

嗯,我无法找到防止这些阴影投射到周围细胞上的好方法,但是我想我找到了一个可行的解决方案。我将添加直接在单元格下面布置的装饰视图,然后将阴影添加到这些视图。这有点骇人听闻,但它应该会产生我想要的效果。

相关问题