ios - 带有图像的 UICollectionView 单元格,通过在 Swift 中单击更改背景

标签 ios swift uicollectionviewcell

我有一个看起来像这样的 Collection View :

enter image description here

蓝色边框是一张图片。当我按下它们时,我希望文本和图像短暂变暗。

我发现这个类似的 SO 问题:

它包括 this answer在 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
    }
}

我尝试将其添加到我的自定义 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
        }
    }
}

但是当我点击一个单元格时,我的收藏 View 没有明显的影响。是我把它添加到错误的地方还是我以错误的方式将它转换为 Swift?

如果我调用方法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

最佳答案

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

请参阅 Swift 中的 UICollectionViewCell 声明。

public var highlighted: Bool

因此您需要像这样覆盖该属性。

class DoubleSoundsCollectionViewCell : UICollectionViewCell {

    override var highlighted: Bool {
        didSet {
            // add your implementation here
        }
    }
}

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

关于ios - 带有图像的 UICollectionView 单元格,通过在 Swift 中单击更改背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32923217/

相关文章:

swift - 动画完成 Collection View Cell 而不是 Image

iOS - 触发来自 Drupal 的密码恢复电子邮件

ios - 在 Windows 7 计算机的 Virtual PC 中运行 OS X?

regex - Swift 正则表达式特殊字符

ios - 尽管桥接头工作正常,但无法在 Swift 中实例化 Obj C 类

ios - 如何在重新加载时清除 UICollectionViewCell?

swift - 从 cellForItemsInSection 中的 #selector 调用带有两个参数的函数

ios - 在 Swift 和 Objective-C 之间共享变量?

ios - delaySubscription 不适用于 rx_tap

ios - 如何使用 Swift 将通知数据传递给 View Controller