我已经看到了类似问题的其他答案,但是即使进行了一些调整,所有解决方案都无法满足我的需求。
正如标题所示,我希望我的UICollectionViewCell
具有圆角和阴影(或除顶部以外的所有侧面的阴影)。到目前为止,我所做的就是在UICollectionViewCell
-mainView
中添加两个视图,该视图显示单元格的必要内容并具有圆角,而shadowView
则具有阴影。两个视图都不是另一个视图的子视图,它们一起存在于同一单元格中。它们都是完全相同的尺寸,mainView
显然显示在shadowView
的顶部。这是我当前的代码实现:
let mainView = cell.viewWithTag(1003) as! UIView
mainView.layer.cornerRadius = 10.0
mainView.layer.borderWidth = 1.0
mainView.layer.borderColor = UIColor.clear.cgColor
mainView.layer.masksToBounds = true
let shadowView = cell.viewWithTag(1002) as! UIView
shadowView.layer.shadowColor = UIColor.black.cgColor
shadowView.layer.shadowOffset = CGSize(width: 0, height: 2.0)
shadowView.layer.shadowRadius = 2.0
shadowView.layer.shadowOpacity = 0.5
shadowView.layer.masksToBounds = false
shadowView.layer.shadowPath = UIBezierPath(roundedRect: shadowView.bounds, cornerRadius: mainView.layer.cornerRadius).cgPath
以下是此代码产生的内容:
有人会认为
mainView
的角不够圆,阴影也不大。
但是,在移除shadowView
并将UICollectionView
的背景设置为黑色后,您可以看到mainView
的角实际上是圆角的:
因此,这意味着问题在于shadowView
的阴影大小。但是,我尝试增加阴影偏移量和阴影半径,但没有任何效果。大多数更改要么在mainView
周围产生很浓的阴影,要么进一步降低mainView
的舍入,要么什么也没做。
答案 0 :(得分:0)
感谢您在环聊中聊天。我下载了您的代码,mainView
和shadowView
为零。
话虽如此。我很高兴介绍我们的朋友Runtime Attributes
无需触摸您的代码。选择一个视图,然后添加runtime attribute key
并设置值。
输出:
继续,为阴影和其余部分进行工作。
mainView
被四舍五入,但是shadowView
占据了所有功劳。
您需要在两个视图上都启用clipsToBounds
:
mainView.clipsToBounds = true
答案 1 :(得分:0)
这是Cell
代码:
class CollectionViewCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
layer.shadowColor = UIColor.lightGray.cgColor
layer.shadowOffset = CGSize(width: 0, height: 2.0)
layer.shadowRadius = 5.0
layer.shadowOpacity = 1.0
layer.masksToBounds = false
layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: contentView.layer.cornerRadius).cgPath
layer.backgroundColor = UIColor.clear.cgColor
contentView.layer.masksToBounds = true
layer.cornerRadius = 10
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
这是用法代码:
import UIKit
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView!.register(CollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
(self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize = CGSize(width: 100, height: 100)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.backgroundColor = .white
return cell
}
}