我有一个名为MyView
的UIView
子类。
它里面有一个UILabel
(由于某些原因,这是通过代码添加而不是在InterfaceBuilder中添加的)。
然后我在MyView
上有一个叫做color
的属性。
我希望Interface Builder能够选择color
,并将标签显示为该颜色的字体。
在我的代码中,我有...
@IBDesignable class MyView: UIView {
private let textLabel = UILabel()
@IBInspectable var color: UIColor = .blackColor() {
didSet {
textLabel.textColor = color
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialSetup()
}
override init(frame: CGRect) {
super.init(frame: frame)
initialSetup()
}
private func initialSetup() -> Void {
self.backgroundColor = .clearColor()
textLabel.textAlignment = .Center
textLabel.numberOfLines = 0
addSubview(textLabel)
}
override func layoutSubviews() {
super.layoutSubviews()
textLabel.frame = bounds
}
// I have no idea what I'm doing here?!
override func prepareForInterfaceBuilder() {
// should I create a label specifically for here?
// or should I use the property textLabel?
textLabel.text = "Hello, world!" // setting place holder IB text?
textLabel.textColor = color
textLabel.font = .systemFontOfSize(21)
textLabel.textAlignment = .Center
textLabel.numberOfLines = 0
// do I need to add sub view?
}
}
IBInspectable
在IB中,我可以看到颜色属性并设置它。但很烦人的是,默认值为`.clearColor()`而不是我在代码中设置的颜色。有没有办法解决这个问题?
IBDesignable
当我将视图放入InterfaceBuilder中时,它显示所有可检查属性,但实际视图中没有显示任何内容。
运行后一切都正常工作。我只想能够在IB中获得其他功能(而非drawRect)。尽管文档相当缺乏,但我仍在寻找方法。
Edit - Warnings
我刚注意到我收到了构建错误/警告,内容如下...
警告:IB Designables: 忽略用户定义的运行时属性"UIView"上的关键路径"color"。在试图设置其值时遇到异常:[setValue:forUndefinedKey:]:此类不能用于键值编码-compliant for the key color。
这可能会改变解决方案 :)
.clearColor()
而不是UIColor.clearColor()
,导致了段错误,但代码中没有显示任何错误。不管怎样,现在一切都正常工作了:D 谢谢! - Fogmeister