You cannot define primitives as nullable for @IBInspectable
s.
When you attempt to do so, and set the value for one of these properties, you'll get the following warning at IBDesignable time:
@IBDesignable class TestDesignable
IB Designables: Ignoring user defined runtime attribute for key path "testInt" on instance of "TestDesignable". Hit an exception when attempting to set its value: [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key testInt.
And at runtime, you'll get the following error:
Failed to set (testInt) user defined inspected property on (TestDesignable): [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key testInt.
To fix it, change it from an optional to non-optional, and give it some zero default value.
Invalid:
@IBDesignable class TestDesignable: UIView {
@IBInspectable var testInt: Int? = nil // crash
@IBInspectable var testFloat: CGFloat? = nil // crash
@IBInspectable var testPoint: CGPoint? = nil // crash
@IBInspectable var testColor: UIColor? = nil
}
Valid:
@IBDesignable class TestDesignable: UIView {
@IBInspectable var testInt: Int = 0
@IBInspectable var testFloat: CGFloat = 0
@IBInspectable var testPoint: CGPoint = .zero
@IBInspectable var testColor: UIColor? = nil
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…