Joe
Joe

Reputation: 3961

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?

Upvotes: 3

Views: 2301

Answers (3)

Phyber
Phyber

Reputation: 1368

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

Upvotes: 2

Paolo
Paolo

Reputation: 3945

UITableView has a method of reusing cells to make it more efficient (keeping only the required cells in memory). Because of this the reused cell may already have this subview, so calling addSubview again causes another view to be added on top of it.

Here is how to solve this:

Move addSubview(overlayView) to the layoutSubviews() method inside your cell subclass.

override func layoutSubviews() {
    super.layoutSubviews()
    addSubview(overlayView)
}

Remove the overlay view in the prepareForReuse() method inside your cell subclass.

override func prepareForReuse() {
    super.prepareForReuse()
    overlayView.removeFromSuperview()
}

Note that this requires you to define the overlay view in the cell's subclass (which you should probably do since the cell itself should be responsible for its own subviews).

Upvotes: 4

Mohammad Sadiq
Mohammad Sadiq

Reputation: 5241

Avoid adding this in cellForItem. The cells are reused, hence if you keep adding the view it would add one top of another. On reusing the cell the previously added view is not removed. Instead you can add the view in Prototype cell or XIB and set its alpha to whatever you want. Or if you are creating the cell programatically you can it in awakeFromNib()

Upvotes: 2

Related Questions