简体   繁体   English

UICollectionView带图像的单元格,在Swift中单击更改背景

[英]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: 它在Objective-C中包括以下答案

If you have a CustomCell, you must have a CustomCell.m (implementation file). 如果您具有CustomCell,则必须具有CustomCell.m(实现文件)。 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: 我尝试将其添加到自定义UICollectionViewCell如下所示:

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? 我是在错误的位置添加了它还是以错误的方式将其转换为Swift?

If I call the method setHighlighed , then I get the error 如果我调用方法setHighlighed ,则会收到错误消息

[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 [PATH] /DoubleSoundsCollectionViewCell.swift:15:10:使用Objective-C选择器'setHighlighted:'的方法'setHighlighted'与具有相同Objective-C选择器的超类'UICollectionViewCell'的'突出显示'的设置方法发生冲突

Because highlighted is a property in Swift. 因为highlighted是Swift中的属性。

See UICollectionViewCell declaration in Swift. 请参见Swift中的UICollectionViewCell声明。

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. 您应该在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. 如果要覆盖某些内容,则必须包含override关键字,如果编译器接受它而没有覆盖,则说明您做错了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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