ios - 无法在 (UIButton) 上设置 () 用户定义的检查属性

标签 ios swift uibutton user-defined

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

screen

按钮是一个@IBOutlet:

@IBOutlet var button:UIButton!

Storyboard中的链接已完成。

我的应用程序中没有其他内容。

我遇到了这个错误:

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 的建议,我创建了一个自定义的 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)!
    }
}

screen2

错误是一样的:

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.

最佳答案

嗯,你的按钮没有一个名为 keyPath 的属性来设置它。

用户定义的运行时属性用于简单地在界面生成器中设置属性值。

您可以使用每个 UIButton 都有的标准属性,例如 backgroundColor:

enter image description here

或者,您可以创建自定义 UIButton 子类,向其添加属性,然后将按钮的类设置为创建的自定义子类,并在用户定义的运行时属性部分设置属性值。

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

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

所以你不能这样做

var keyPath: Bool!

相反你只能做

var keyPath: Bool = false

或者不使用默认值,而是在构造函数中设置它。出于某种原因,它与可选的 String 一起使用(在示例中,它们使用可选的 String),但不适用于可选的 Bool .总而言之,不要过度使用或担心用户定义的运行时属性,在代码中设置默认值更清晰!

希望对您有所帮助!祝你好运!

关于ios - 无法在 (UIButton) 上设置 () 用户定义的检查属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43032924/

相关文章:

ios - 从 Xcode 打印的字典日志创建 NSDictionary

ios - Swift:为 CustomTab 重用一个 ViewController

ios - 将字符串属性添加到 Swift 中的 UIButton

使用 1 个菜单和许多 UIPopoverController 的基本应用程序的 iOS 设计模式......?

ios - 如何在 Swift 中创建具有自定义形状的 UIButton?

ios - GMSAutocompleteViewController 删除 "cancel"按钮

ios - FetchRequest - NSArray 元素无法匹配 Swift 数组元素类型 - Swift 2.0

ios - 无法在 iTunes Connect 上创建初始应用内购买,因为产品类型列表为空

swift - 如何在标签栏上方底部的所有 View Controller 中添加一个公共(public) View

ios - 从 UITabBarController 调用 SFSafariViewController 并在按下 "Done"后返回