Search code examples
iosiphonexcodestoryboardibdesignable

iOS Designable Button Background color don't work


I created a custom UIButton with this code:

@implementation HGButton

- (instancetype)initWithFrame:(CGRect)frame
 {
    if (self = [super initWithFrame:frame]) {
        [self initVariables];
        [self customInit];
    }

    return self;
}

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

- (void)drawRect:(CGRect)rect
{
    [self customInit];
}

- (void)setNeedsLayout
{
    [super setNeedsLayout];
    [self setNeedsDisplay];
}

- (void)prepareForInterfaceBuilder
{
    [self customInit];
}

-(void) initVariables
{
    self.fillColor          = [UIColor lightGrayColor];
    self.borderWidth        = 2;
    self.cornerRadious      = 10;
}

- (void)customInit
{
    [self setBackgroundColor:self.fillColor];

    self.layer.cornerRadius = self.cornerRadious;
    self.layer.borderWidth = self.borderWidth;

    if (self.cornerRadious > 0) {
        self.layer.masksToBounds = YES;
    }
}

it's a very simple code. When add my button to a view in storyboard it looks perfect. But when I play the app the button background color is always light grey. When I press the button it's background color change to the color selected in storyboard.

Why this? Where is the error?


Solution

  • Because you are not updating the background color when self.fillcolor has been changed through storyboard.

    Assuming you have this

    @property (nonatomic, copy)   IBInspectable UIColor *fillcolor;
    

    Add the following code in your class

    - (void)setFillColor:(UIColor *)fillColor {
        if (fillColor != _fillColor) {
            _fillColor = fillColor;
            [self customInit];
        }
    }
    

    Hope this helps.

    Cheers.