gpt4 book ai didi

ios - 防止 UICollectionViewCell 阴影转换到其他单元格上

转载 作者:行者123 更新时间:2023-12-01 19:00:02 27 4
gpt4 key购买 nike

我希望有人能有一个聪明的解决方案来解决这个问题,因为目前我很困惑。我有一个 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

谢谢!

最佳答案

设置 Collection View 图层的阴影属性,而不是在每个单元格上设置它们。确保 Collection View 没有 backgroundView 并且它的 backgroundColor 为零。还要确保 Collection View 的某些祖先 View 确实具有背景颜色或其他填充。

结果:

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
}

}

关于ios - 防止 UICollectionViewCell 阴影转换到其他单元格上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54314845/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com