UITableViewCell堆叠层

问题描述

我有一个自定义UITableViewCell,其中包含图像,我在UIImageView添加了扩展名,并在其中添加了一层以覆盖较浅的颜色。

enter image description here

func overlay(widht: CGFloat,height: CGFloat,color: UIColor) {
    let colorOverlay = CALayer()
    colorOverlay.frame = CGRect(x: 0,y: 0,width: widht,height: height)
    colorOverlay.backgroundColor = color.cgColor
    
    self.layer.addSublayer(colorOverlay)
    self.layer.masksToBounds = true
}

这里的问题是,每次重新使用单元格时,都会添加该层,因此它们会堆叠在一起,直到图像不再可见并且所有可见的都是灰色矩形

enter image description here

self.image.overlay(widht: self.image.frame.width,height: self.image.frame.height,color: UIColor.gray)

如何防止图层堆叠?或者如何在不使用适用于可重用单元格的CALayer()的情况下为图像添加覆盖色

解决方法

问题应该是您在每次配置单元格时都将叠加层添加到图像视图中。请记住,如果适用,UITableView重用同一单元实例。通过什么来控制视觉输出是完全开放的。但是请确保您的代码在这里运行两次是否不会导致任何不同或不会限制该代码段的执行一次。