Search code examples
iosswiftuicollectionviewuicollectionviewcelladdsubview

Adding an overlay view to UICollectionViewCell - keeps overlaying


I'm trying to add a 50% black alpha view on every collection view cell. The collection view cells have a background photograph and text on top. Would like the overlay view to be in between the two.

In my cellForItemAt method, I use the following:

let overlayView = UIView()
overlayView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
overlayView.frame = cell.bounds
cell.addSubview(overlayView)

The problem is as i scroll down, then up, the overlay keeps adding, making the alpha much darker than 50%. Additionally, the overlayView is being added on top of my text (I need it below the text.)

How can I prevent the overlay from adding multiple times, and adding it in between the correct layers of the cell?


Solution

  • This happens because your cells are dequeued and reused multiple times, therefore, you are adding multiple layers.

    Put this code inside your cell's class

    override func awakeFromNib() {
        super.awakeFromNib()
        let overlayView = UIView()
        overlayView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
        overlayView.frame = self.bounds
        self.addSubview(overlayView)
    }
    

    Or if you want to achieve the same result you can set black backgroundColor and set imageView's alpha to 50%

    cell.backgroundColor = .black
    cell.imageView.alpha = 0.5