【发布时间】:2019-04-28 08:14:33
【问题描述】:
我有一个带有 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'
我怎样才能让它工作?
【问题讨论】: