Hatchmaster J
Hatchmaster J

Reputation: 561

Programmatically setting a User Defined Runtime Attribute

I added a User Defined Runtime Attribute to a UIButton using Interface Builder. The attribute is named strokeColor, and is of type Color.

I try to set it programmatically, as follows:

UIColor *someColor = [UIColor yellowColor];
[myButton setValue:someColor forKey:@"strokeColor"];

The second line crashes, and I get the following error:

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

What might be the cause of this exception? What data type does a user defined runtime attribute of type color expect?

Upvotes: 1

Views: 1960

Answers (1)

memmons
memmons

Reputation: 40502

Runtime attributes allow you to access properties of objects that would not otherwise be surfaced in Interface Builder, but you still have to define any properties you are accessing via a runtime attribute. Simply adding a runtime attribute to a class which doesn't have a matching property will throw an exception, as you have seen.

In your case, if you want to be able to set a property named strokeColor on a UIButton via a runtime attribute, first you must create a UIButton subclass or category that has the property, then you will be able to set it's corresponding runtime attribute;

Here's a UIButton category:

@interface UIButton (Coloring)

@property (nonatomic, strong) UIColor *strokeColor;

@end

Upvotes: 1

Related Questions