我在 UIViewController
中有一个 UICollectionView
。我使用以下扩展将 UICollectionViewCell
配置为具有圆角和阴影:
extension UICollectionViewCell {
func configureCell() {
self.contentView.layer.cornerRadius = 5.0
self.contentView.layer.borderWidth = 1.0
self.contentView.layer.borderColor = UIColor.clear.cgColor
self.contentView.backgroundColor = UIColor.white
self.contentView.layer.masksToBounds = true
self.layer.shadowColor = UIColor.lightGray.cgColor
self.layer.shadowOffset = CGSize.zero
self.layer.shadowRadius = 2.0
self.layer.shadowOpacity = 1.0
self.layer.masksToBounds = false
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.contentView.layer.cornerRadius).cgPath
}
}
最初绘制 UICollectionView
时,会在单元格上绘制圆角和阴影。然而,当我移动单元格时,角开始消失,但阴影仍然存在。我想我只需要更新单元格,所以我将其添加到 moveItemAt
:
func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
[collectionView.cellForItem(at: sourceIndexPath), collectionView.cellForItem(at: destinationIndexPath)].forEach({$0?.configureCell()})
}
这不起作用,所以我尝试了这个:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.visibleCells.forEach({$0.configureCell()})
}
相同的结果...圆角消失,但阴影仍然存在。
我欢迎有关如何在移动 UICollectionViewCells
时保持圆角的建议。感谢您的阅读。
更新:
经过进一步修改,我发现每次在初始 View 加载后单击单元格时,单击单元格时圆角都会变成方形。所以我尝试了这个:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.cellForItem(at: indexPath)?.configureCell()
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
collectionView.cellForItem(at: indexPath)?.configureCell()
}
最佳答案
我确定问题出在我的扩展中。我不是 100% 确定为什么它最初绘制正确并且不更新,但我需要取出 contentView
引用并直接转到layer
.
我还把configureCell()
的所有引用都拿出来了来自其他方法的调用。它按预期工作。这是它的样子。
extension UICollectionViewCell {
func configureCell() {
self.layer.cornerRadius = 5.0
self.layer.borderWidth = 1.0
self.layer.borderColor = UIColor.clear.cgColor
self.backgroundColor = UIColor.white
self.layer.masksToBounds = true
self.layer.shadowColor = UIColor.lightGray.cgColor
self.layer.shadowOffset = CGSize.zero
self.layer.shadowRadius = 2.0
self.layer.shadowOpacity = 1.0
self.layer.masksToBounds = false
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.contentView.layer.cornerRadius).cgPath
}
}
关于ios - UICollectionViewCell 呼吸时圆角恢复为方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42671803/