是否有可能在旋转的情况下发生 UICollectionViewCell 渐变背景层渲染问题?

Is it possible that UICollectionViewCell gradient background layer render issue happens in case of rotation?

所以我有一个自定义 UICollectionViewController,它包含简单的矩形单元格 (UICollectionViewCell)。我想用圆角和渐变背景颜色自定义这些。我可以通过为 viewcontroller.

中的单元格设置适当的参数来实现这一点

但是,在旋转的情况下,我的单元格会“崩溃”,就像渲染有问题一样。你认为我遗漏了什么,还是我应该以完全不同的方式来做?

代码

override func collectionView(
        _ collectionView: UICollectionView,
        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = self.collectionView
            .dequeueReusableCell(withReuseIdentifier: self.reuseIdentifier,
                                 for: indexPath) as? AllCollectionViewCell  else {
            fatalError("The dequeued cell is not an instance of AllCollectionViewCell.")
        }
    
        // Configure the cell
        cell.layer.cornerRadius = 15;
        cell.layer.masksToBounds = true
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.5)
        gradientLayer.colors = [UIColor.red.withAlphaComponent(0.3).cgColor,
                                UIColor.red.withAlphaComponent(0.7).cgColor]
        
        gradientLayer.frame = cell.bounds

        cell.backgroundView = UIView()
        cell.backgroundView?.layer.addSublayer(gradientLayer)
        
        return cell
    }

这个问题不是绝对可以预测的,但是在旋转(横向视图后返回纵向)和滚动之后经常发生.

预计

https://i.imgur.com/tGvauZG.png

问题

https://i.imgur.com/DRPZjcD.png

我试过了,但我没有遇到 UI 错误。你可以把你的代码发给我,让我看看你是否想要。 但总的来说,我认为为了更好的练习,你应该在它的单元格 class AllCollectionViewCell

上移动单元格 UI 代码

我尝试按照 canister_exister and Mohamed Shaban 的建议在单元格 class 本身 (AllCollectionViewCell) 中设置属性,它 部分 解决了它:

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    self.layer.cornerRadius = 15;
    self.layer.masksToBounds = true

    let gradientLayer = CAGradientLayer()
    gradientLayer.frame = self.bounds
    gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.5)
    gradientLayer.endPoint = CGPoint(x: 0.0, y: 0.5)

    self.backgroundView = UIView()
    self.backgroundView?.layer.addSublayer(gradientLayer)
}

但是gradientLayer的frames就是不符合我的预期,所以我再找了找,发现应该放​​在另外一个function里面。所以我将 gradientLayer 移动到 class 属性,然后覆盖这个函数:

override func layoutSubviews() { self.gradientLayer.frame = self.bounds }

感谢您提供有用的答案!