Suragch
Suragch

Reputation: 511586

UICollectionView Cell with Image, change Background with click in Swift

I have a Collection View that looks like this:

enter image description here

The blue border is an image. When I press them I want the text and the image to dim briefly.

I found this SO question that is similar:

And it included this answer in Objective-C:

If you have a CustomCell, you must have a CustomCell.m (implementation file). In this file add this, to me is the easy way:

-(void)setHighlighted:(BOOL)highlighted
{
    if (highlighted)
    {
        self.layer.opacity = 0.6;
        // Here what do you want.
    }
    else{
        self.layer.opacity = 1.0;
        // Here all change need go back
    }
}

I tried adding this to my custom UICollectionViewCell like this:

import UIKit

class DoubleSoundsCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var cellLabel: UILabel!

    func highlighted(highlighted: Bool) {
        if (highlighted)
        {
            self.layer.opacity = 0.6;
            // Here what do you want.
        }
        else{
            self.layer.opacity = 1.0;
            // Here all change need go back
        }
    }
}

But there was no noticeable effect on my collection view when I tap a cell. Did I add it in the wrong place or did I convert it to Swift in the wrong way?

If I call the method setHighlighed, then I get the error

[PATH]/DoubleSoundsCollectionViewCell.swift:15:10: Method 'setHighlighted' with Objective-C selector 'setHighlighted:' conflicts with setter for 'highlighted' from superclass 'UICollectionViewCell' with the same Objective-C selector

Upvotes: 0

Views: 807

Answers (1)

mohamede1945
mohamede1945

Reputation: 7198

Because highlighted is a property in Swift.

See UICollectionViewCell declaration in Swift.

public var highlighted: Bool

So you will need to override the property like this.

class DoubleSoundsCollectionViewCell : UICollectionViewCell {

    override var highlighted: Bool {
        didSet {
            // add your implementation here
        }
    }
}

You should always know in Swift. You have to include override keyword if you are overriding something, if the compiler accept it without override, then you are doing something wrong.

Upvotes: 1

Related Questions