How to set default values for IBInspectable in Objective-C?

Can Poyrazoğlu picture Can Poyrazoğlu · Nov 20, 2014 · Viewed 28.1k times · Source

I know default values of IBInspectable-properties can be set as:

@IBInspectable var propertyName:propertyType = defaultValue in Swift. But how do I achieve a similar effect in Objective-C so that I can have default value of some property set to something in Interface Builder?

Answer

rintaro picture rintaro · Nov 21, 2014

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