Search code examples
iospropertiessubclassing

How to create init methods for UIViews in storyboard?


I have a class PLButton with two properties:

@property (strong, nonatomic) UIColor *purpleColor;
@property (strong, nonatomic) UIColor *grayColor;

and its initializer:

- (instancetype)init {
if (self = [super init]) {
    self.purpleColor = [UIColor colorWithRed:142.0/255.0 green:23.0/255.0 blue:126.0/255.0 alpha:1.0];
    self.grayColor = [UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:239.0/255.0 alpha:1.0];
}
return self;

}

Also I have a PLEventButton as a subclass of PLButton:

and initializer inside:

- (instancetype)init {
if (self = [super init]) {
    return self;
}
return self;

}

Those classes I assign in storyboard to UIButtons. Why those properties are not working at all in both: PLButton and PLEventButton (they are nil)?


Solution

  • Object in storyboard are init by the initWithCoder method. So just call your initialization method within.

     - (id)initWithCoder:(NSCoder*)aDecoder 
    {
        self = [super initWithCoder:aDecoder];
        if (self)
        {
            [self myInitialization];
        }
    
        return self;
    }