简体   繁体   中英

UICollectionView Cell with Image, change Background with click in Swift

I have a Collection View that looks like this:

在此处输入图片说明

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM