我有一个 UICollectionView
,每行有 3 个单元格。我需要设置 topLeft
和 bottomLeft
cornerRadius
到左边,topRight
和 bottomRight
到正确的那个。中间那个没有 cornerRadius
。
设置cornerRadius的扩展方法
func setRadius(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
我已经使用这段代码找出哪个单元格需要有 cornerRadius。
let index = indexPath.row
if index == 0 || index % 3 == 0 {
cell.setRadius(corners: [.topLeft, .bottomLeft], radius: TPSetting.cornerRadius)
}
else if ( index - 2) % 3 == 0 {
cell.setRadius(corners: [.topRight, .bottomRight], radius: TPSetting.cornerRadius)
} else {
cell.layer.cornerRadius = 0
}
这是第一次按预期工作。但是当调用 collectionView.reloadData()
时,它就搞砸了,中间的那个也得到了 topRight
和 bottomRight cornerRadius
。
如何解决这个问题?
最佳答案
当您滚动/重新加载数据时,单元格被重用而不被释放。这是预期的行为。
为了“重置”对角半径所做的更改,您可以:
- 子类细胞。
- 覆盖子类中的
prepareForReuse
方法以撤消在setRadius
方法中引入的更改。 Docs - 不要忘记在覆盖方法中调用
super.prepareForReuse
。
将代码放在方法中:
self.layer.mask = nil
self.layer.cornerRadius = 0
关于ios - 在每行 3 个单元格布局中将 cornerRadius 添加到第一个和第三个 UICollectionViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56410751/