I'm trying to add an IBInspectable
color to UIView, so that I can set it in the storyboard and later use it in code. In this post regarding UITextField I've seen that I can take advantage of extensions and adding a computed property, but I can't make it work for UIView.
I get a crash: Failed to set (additionalColor1) user defined inspected property on (UIView): [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key additionalColor1.
Any idea what's causing the crash and how to fix it?
Here's my code:
extension UIView {
@IBInspectable var additionalColor1: UIColor? {
return self.additionalColor1
}
}
For the reference, I'm pasting the code that can be used to set the placeholder color for UITextField (same as the above url). This works ok:
extension UITextField {
@IBInspectable var placeHolderColor: UIColor? {
get {
return self.placeHolderColor
}
set {
self.attributedPlaceholder = NSAttributedString(string: self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!])
}
}
}
self.additionalColor1
should be set in storyboard. I've pasted the image showing that I've set it in identity inspector. In my pasted snipped I haven't impelemented a setter. However, addingself.additionalColor1 = newValue
to a setter does still result in a crash. – Improvisationset
andget
it's supposed to be aget
only property. It looks like when you set the color in the above way you can only use it within the scope of the setter (eg. for changing "internal" properties). The getter doesn't make any sense and can easily return nil all the time. – Improvisation