Search code examples
ioscocoa-touchibdesignable

Button label color change doesn't work if font is also changed


Here is a simple example custom button that is set as a class of a button in IB:

#import "TestButton.h"
@implementation TestButton

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    UIFont * font = [UIFont systemFontOfSize:8];
    if ( self.setFont )
        self.titleLabel.font = font;
    self.titleLabel.textColor = [UIColor redColor];
}

@end

If setFont is false, that is, the font is unchanged, the the label text color is red as expected. But if it is true, the button text color is whatever it is set to in IB.

So the question is what's going on here, and how can I change both the text and the font of a button that is assigned in IB programmatically.

In case someone wants to see these peculiarities and also how funky IBDesignable can be, see demo project


Solution

  • Replace

    self.titleLabel.textColor = [UIColor redColor];
    

    with

    [self setTitleColor:[UIColor redColor] forState:UIControlStateNormal];