使用 UICollectionCell 获取 属性 不会覆盖 Swift 中其超类中的任何 属性

Getting Property does not override any property from its superclass in Swift with UICollectionCell

extension UICollectionViewCell
{
  override var isSelected: Bool
   {
        didSet {
            backgroundColor = isSelected ? UIColor.black : UIColor.blue
        }
    }
}

我正在尝试覆盖 UICollectionView Cell 中的 isSelected 变量,但我收到一条错误消息,指出“获取 属性 不会覆盖其超类中的任何 属性”。

UICollectionViewCell 进行扩展正是这样做的, 扩展了 UICollectionViewCell class 功能,而无需对其进行子class . isSelected 属性 已在同一个 class 中声明。

如果你想覆盖isSelected 属性你必须subclass UICollectionViewCell,比如:

class MyCollectionViewCell: UICollectionViewCell {
    override var isSelected: Bool {
        didSet {
            backgroundColor = isSelected ? .black : .blue
        }
    }
}

您可以在官方文档中找到 extensions 的更多信息。