Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 780
Can Poyrazoğlu Avatar asked Nov 20 '14 15:11

Can Poyrazoğlu


People also ask

What is@ IBInspectable?

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.

What is IBDesignable and IBInspectable?

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.


2 Answers

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 
like image 152
rintaro Avatar answered Oct 01 '22 11:10

rintaro


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; } 
like image 29
GetToSet Avatar answered Oct 01 '22 13:10

GetToSet