UICollectionView Cell with Image, change Background with click in Swift

女生的网名这么多〃 提交于 2019-12-13 03:37:30

问题


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:

  • UICollectionView Cell with Image, change Background with click

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


回答1:


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.



来源:https://stackoverflow.com/questions/32923217/uicollectionview-cell-with-image-change-background-with-click-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!