我有一个带有IBInspectable颜色属性的自定义UIView类:
class MyParent: UIView {
// use CGColor for setting background (a gradient), and IBInspectable UIColor to choose color in Interface Builder
var color1: CGColor = UIColor(red: 100.0/255.0, green: 130.0/255.0, blue: 230.0/255.0, alpha: 1.0).CGColor
var color2: CGColort = UIColor(red: 200.0/255.0, green: 30.0/255.0, blue: 30.0/255.0, alpha: 1.0).CGColor
@IBInspectable var UIcolor1: UIColor = UIColor(red: 100.0/255.0, green: 130.0/255.0, blue: 230.0/255.0, alpha: 1.0) {
didSet {
color1 = UIcolor1.cgColor
}
}
// INIT: Set gradient with color1/2 for the background of MyParent view
override init(frame: CGRect) {
super.init(frame: frame);
var gradient = CAGradientLayer()
gradient.frame = bounds
gradient.colors = [color1, color2]
layer.insertSublayer(gradient, at: 0)
}
}
更新以进行澄清:这样做是为了能够在Interface Builder中选择一种颜色(仅适用于UIColor),但是由于视图的背景是渐变,它需要转换为CGColor。因此,didSet完成了这项工作,并且在IB中选择了UIColor之后,背景分别发生了变化。
现在我想拥有另一个自定义UIView,它是MyParent的子类,我想设置另一个默认的UIcolor1,但出现错误:
class MySubclass: MyParent {
// override UIcolor1
override var UIcolor1: UIColor = UIColor.blue
// ...
}
以下错误:
Cannot override the stored property 'UIcolor1'
我该如何工作?
答案 0 :(得分:1)
如果您不想在初始设置颜色,我认为您可以在这里做到最好
class MySubclass: MyParent {
// override UIcolor1
override var UIcolor1: UIColor {
get {
return .blue
}
set {
color1 = newValue.cgColor
}
}
// ...
}
代码修改后
我认为这种子类化视图的用法是不必要的。这是工作代码
@IBDesignable
class MyParent: UIView {
// use CGColor for setting background, and IBInspectable UIColor to choose color in Interface Builder
var color1: UIColor = UIColor.blue {
didSet {
gradientLayer.colors = [color1.cgColor, color2]
}
}
var color2: CGColor = UIColor.green.cgColor
@IBInspectable var inspectableColor1: UIColor {
get {
return color1
}
set {
color1 = newValue
}
}
private var gradientLayer = CAGradientLayer()
// INIT: Set color1 for the background of MyParent view
// ...
override init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayer()
}
func setupLayer() {
gradientLayer.frame = bounds
gradientLayer.colors = [color1.cgColor, color2]
layer.insertSublayer(gradientLayer, at: 0)
}
}