在(UIButton)上设置()用户定义的检查属性失败

在一个简单的ViewController中,我添加了一个UIButton。 我想使用“用户定义的运行时属性”。 现在我添加了默认的Bool属性。

屏幕

该button是@IBOutlet:

@IBOutlet var button:UIButton! 

故事板中的链接已完成。

我的应用程序中没有其他东西。

我得到这个错误:

 2017-03-26 20:31:44.935319+0200 ISAMG[357:47616] Failed to set (keyPath) user defined inspected property on (UIButton): [<UIButton 0x15e3a780> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key keyPath. 

我不明白我错过了什么。

编辑1

遵循@timaktimak的build议,我创build了一个自定义的UIButton类:

 @IBDesignable class ChoiceButton: UIButton { @IBInspectable var keyPath: Bool! { didSet { print("didSet viewLabel, viewLabel = \(self.keyPath)") } } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } } 

画面2

错误是一样的:

 2017-03-26 22:32:27.389126+0200 ISAMG[429:71565] Failed to set (keyPath) user defined inspected property on (ISAMG.ChoiceButton): [<ISAMG.ChoiceButton 0x14e8f040> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key keyPath. 

那么,你的button没有一个叫做keyPath的属性来设置它。

用户定义的运行时属性用于简单地在Interface Builder中设置属性值。

你可以使用每个UIButton的标准属性,例如backgroundColor

在这里输入图像说明

或者,您可以创build一个自定义UIButton子类,向其添加属性,然后将该button的类设置为创build的自定义子类,并在“用户定义的运行时属性”部分中设置属性值。

例如,您可以查看此答案,其中包含具有用户定义的运行时属性的自定义类的示例: https : //stackoverflow.com/a/24433125/3445458

编辑:确保你没有使用可选(或隐式解包可选)的types,它不适用于用户定义的运行时属性(我猜是因为界面生成器不知道该值是否可以设置为零,所以在选项中显示或不)。

所以你不能这样做

 var keyPath: Bool! 

相反,你只能这样做

 var keyPath: Bool = false 

或者不要使用默认值,而是将其设置在构造函数中。 出于某种原因,它与一个可选的String (在这个例子中他们使用一个可选的String ),但它不与可选的Bool 。 总而言之,不要太担心用户定义的运行属性,在代码中设置默认值会更清楚。

希望这可以帮助! 祝你好运!

在用户定义的运行时属性中,使用layer.cornerRadius而不是cornerRadius

Interesting Posts