带有图像的 UICollectionView 单元格,在 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:

它在 Objective-C 中包含了这个答案:

And it included this answer in Objective-C:

如果你有一个 CustomCell,你必须有一个 CustomCell.m(实现文件).在这个文件中添加这个,对我来说是简单的方法:

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
    }
}

我尝试将其添加到我的自定义 UICollectionViewCell 中,如下所示:

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
        }
    }
}

但是当我点击一个单元格时,我的收藏视图没有明显的影响.我是在错误的地方添加了它,还是以错误的方式将其转换为 Swift?

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?

如果我调用方法 setHighlighted,我会得到错误

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

[路径]/DoubleSoundsCollectionViewCell.swift:15:10: 方法'setHighlighted' 与 Objective-C 选择器 'setHighlighted:' 冲突带有来自超类UICollectionViewCell"的突出显示"的设置器使用相同的 Objective-C 选择器

[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

因为 highlighted 是 Swift 中的一个属性.

Because highlighted is a property in Swift.

参见 Swift 中的 UICollectionViewCell 声明.

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
        }
    }
}

您应该始终知道 Swift.如果您要覆盖某些内容,则必须包含 override 关键字,如果编译器在没有覆盖的情况下接受它,那么您就做错了.

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.