How to set default values for IBInspectable in Objective-C?
Since IBInspectable
values are set after initWithCoder:
and before awakeFromNib:
, you can set the defaults in initWithCoder:
method.
@interface MyView : UIView
@property (copy, nonatomic) IBInspectable NSString *myProp;
@property (assign, nonatomic) BOOL createdFromIB;
@end
@implementation MyView
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if(self != nil) {
self.myProp = @"foo";
self.createdFromIB = YES;
}
return self;
}
- (void)awakeFromNib {
if (self.createdFromIB) {
//add anything required in IB-define way
}
NSLog(@"%@", self.myProp);
}
@end
I wrote my code like this. It works pretty well for me, both when designing in the interface builder or running as a app.
@interface MyView : UIView
@property (copy, nonatomic) IBInspectable propertyType *propertyName;
@end
- (void)makeDefaultValues {
_propertyName = defaultValue;
//Other properties...
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
[self makeDefaultValues];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[self makeDefaultValues];
}
return self;
}