user3755632
user3755632

Reputation: 381

Add overlay to UIImageView in a custom UICollectionViewCell

I have a custom UICollectionViewCell class with a few properties:

class SimpleCollectionCell: UICollectionViewCell {

    @IBOutlet weak var title_more: UILabel!

    @IBOutlet weak var image_more: UIImageView!

    @IBOutlet weak var title: UILabel!

    @IBOutlet weak var distance: UILabel!

    @IBOutlet weak var activity: UIImageView!

}

My method for populating the data is as so:

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! SimpleCollectionCell

    var place = Place()

    // set the current place
    place = Places[indexPath.row]

    // set the label
    cell.title.text = place.title

    // setup url
    let url = NSURL(string: currentThing.imageUrl!)

    // set the cell image
    cell.activity.hnk_setImageFromURL(url!)

    return cell

}

The cell renders as it should and displays as so:

UICollectionViewCells

My question is how can I make the images darker?

I have tried to add the following code at the bottom of the cellForItemAtIndexPath method but it gets darker as you scroll because it keeps on adding more sub views!

// Create a subview which will add an overlay effect on image view
let overlay: UIView = UIView(frame: CGRectMake(0, 0, cell.activity.frame.size.width, cell.activity.frame.size.height))
    overlay.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3);

// Add the subview to the UIImageView
cell.activity.addSubview(overlay)

Upvotes: 2

Views: 1194

Answers (1)

Mattias
Mattias

Reputation: 2306

A quick solution would be to check to see if an overlay was already added to the cell, and if so not add another one.

Using tags:

if cell.activity.viewWithTag(99) == nil {
    // Create a subview which will add an overlay effect on image view
    let overlay = UIView(frame: CGRect(x: 0, y: 0, width: cell.frame.size.width, height: cell.frame.size.height))
    overlay.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3);
    overlay.tag = 99

    // Add the subview to the UIImageView
    cell.activity.addSubview(overlay)
}

Or just create the overlay from within the cell.

Upvotes: 3

Related Questions