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?
The @IBInspectable keyword lets you specify that some parts of a custom UIView subclass should be configurable inside Interface Builder. Only some kinds of values are supported (booleans, numbers, strings, points, rects, colors and images) but that ought to be enough for most purposes.
IBDesignable is user defined run time. Mean that if any IBDesignable view is rendered on the storyboard, you will find the view and change the value of the IBInspectable property, this will directly reflect on the storyboard without running the app. IBInspectable is run time property, this works as key coding value.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With