UIButton这个类不是键的键值代码兼容

时间:2017-08-03 12:39:03

标签: ios uibutton storyboard

我有以下代码行:

[self.someBtn setValue:@"some-value" forKey:@"some-key"];

其中someBtn从故事板绑定。 问题是我收到了这个错误:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<UIButton 0x137e7deb0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key some-key.'

如果我评论这行代码就可以了。我想通过使用setValue:forKey函数通过UIButton传递一些“元”信息。

有人可以向我解释发生了什么吗?谢谢!

2 个答案:

答案 0 :(得分:1)

最简单的方法是在按钮上添加一些值&#34;通过相关对象。您可以为UIButton编写一个扩展名

@interface UIButton (AssociatedObject)

@property (nonatomic, strong) id associatedObject;

@end

@implementation UIButton (AssociatedObject)
@dynamic associatedObject;

- (void)setAssociatedObject:(id)object {
     objc_setAssociatedObject(self, @selector(associatedObject), object, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (id)associatedObject {
    return objc_getAssociatedObject(self, @selector(associatedObject));
}

您可以阅读涵盖相关对象使用的very good article on NSHipster

请注意,无论您尝试实际做什么,都可以通过继承按钮或将值存储在其他地方来更轻松地完成。

答案 1 :(得分:0)

您无法通过UIButton传递任何信息。你只能在你的UIButton中将int设置为标签 -

self.someBtn.tag = 1;