使用协议覆盖 UIButton backgroundColor 属性

Override UIButton backgroundColor property with protocol

我有一个类似的协议

protocol ButtonPresentable {
    var backgroundColor: UIColor { get }
}

extension ButtonPresentable {
    var backgroundColor: UIColor? {
        return UIColor.red
    }

}

我有一个自定义按钮 class(使用 IB 绘制)实现了我的协议

class MyButton: UIButton, ButtonPresentable {
}

为什么这个协议没有 'override' 原生 backgroundColor 属性?

我想要一个默认协议实现,它将为所有按钮设置默认背景。是否有面向协议的方式来为所有 UIButton 背景颜色设置默认值?

编辑:实际上我就是这么做的

protocol ButtonPresentable {
    var pBackgroundColor: UIColor { get }
}

extension ButtonPresentable {
    var pBackgroundColor: UIColor? {
        return UIColor.red
    }

    func applyTheme() {
        self.backgroundColor = pBackgroundColor
    }
}

// In my custom view
required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    self.applyTheme()
}

1.为什么这个协议不 'override' 原生 backgroundColor 属性 ?

因为:Extensions can add new functionality to a type, but they cannot override existing functionality.

看这个例子:

protocol ButtonProtocol {
  var name: String { get }
}

extension ButtonProtocol {
  var name: String {
    return "button protocol"
  }
}

class ButtonClass: ButtonProtocol {
  var name: String = "button class"
}

let button = ButtonClass()
print(button.name) // prints: button class

2。是否有面向协议的方式来为所有 UIButton 背景颜色设置默认值?

如果你想覆盖所有按钮的backgroundColor,你可以这样做:一旦按钮设置了它的框架,你就可以覆盖它的背景颜色:

extension UIButton {
  open override var frame: CGRect {
    didSet {
      self.backgroundColor = .red
    }
  }
}