ios - 在每行 3 个单元格布局中将 cornerRadius 添加到第一个和第三个 UICollectionViewCell

标签 ios swift uicollectionview uicollectionviewcell

我有一个 UICollectionView,每行有 3 个单元格。我需要设置 topLeftbottomLeft cornerRadius 到左边,topRightbottomRight 到正确的那个。中间那个没有 cornerRadius

Cell looks like this

设置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() 时,它就搞砸了,中间的那个也得到了 topRightbottomRight 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/

相关文章:

cocoa - 将键盘输入数据传递给 View Controller

ios - 选项卡和 webView

ios - 静态分组 TableView 单元格

ios - 在 UICollectionViewCell 中以编程方式添加的 UIButton 不起作用

ios - 委托(delegate)函数在删除 CollectionView 项目 Swift 时无法正确调用

ios - 移动索引路径后 UITableviewCell 内的 UICollectionView

ios - 比数据参数更多的 '%' 转换

ios - 使用 https ://asmx-based service with Monotouch

ios - 多点连接崩溃尝试从对象 [2] 插入零对象

ios - 设置数据库中索引值的数组