UICollectionView Cell with image, changing background with click in Swift
I have a Collection View that looks like this:
The blue frame is the image. When I click them I want the text and image to dim briefly.
I found this SO question to be similar:
And he included this answer in Objective-C:
If you have CustomCell, you should have CustomCell.m (implementation file). In this file add this, for me it's an 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 to add this to my custom one 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 discernible effect on my collection view when I click on a cell. Did I add it in the wrong place or did I convert it to Swift in a different way?
If I call the method setHighlighed
, then I get the error
[PATH] /DoubleSoundsCollectionViewCell.swift:15:10: method 'setHighlighted' with Objective-C selector 'setHighlighted:' conflict with setter for 'highlighted' from superclass 'UICollectionViewCell' with same Objective-C selector
source to share
Because it highlighted
is a property in Swift.
See declaration UICollectionViewCell
in Swift.
public var highlighted: Bool
So you need to override a property like this.
class DoubleSoundsCollectionViewCell : UICollectionViewCell {
override var highlighted: Bool {
didSet {
// add your implementation here
}
}
}
You should always know in Swift. You must include the override keyword if you are overriding something, if the compiler accepts it without overriding then you are doing something wrong.
source to share