我有一个名为MyView的UIView的子类,我正在创建它.
在其中有一个UILabel(由于原因,这是在代码中添加而不是在InterfaceBuilder中).
然后,我在MyView上有一个名为color的属性.
我想要的是让Interface Builder能够选择颜色,然后显示标签,并将字体设置为该颜色.
在我的代码中我有……
@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).我发现明显缺乏文档.
编辑 – 警告
我刚注意到我发现构建错误/警告说…
warning: IB Designables: Ignoring user defined runtime attribute for key path “color” on instance of “UIView”. Hit an exception when attempting to set its value: [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key color.
这可能会改变解决方案:)
解决方法
我将你的问题中的代码复制到一个新的应用程序中,添加了视图并设置了属性,它运行得很好.
您看到的错误表明您在某些时候已将视图更改回身份检查器中的普通UIView(在这种情况下,用户定义的属性仍然存在).