zlog
zlog

Reputation: 3316

How do I set the highlighted title colour of a subclassed UIButton?

I've subclassed UIButton and am trying to set the title colour when the button is highlighted. The custom button is also on a nib file.

I have the code:

- (void)layoutSubviews 
{
    [super layoutSubviews];

    self.titleLabel.textColor = [UIColor blueColor];
    [self setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted]; // Offending line

}

However, the view does not load (seemingly goes into an infinite loop and doesn't show) when I have the setTitleColor:forState: line. Is it supposed to be declared elsewhere? How else do you set the highlighted title colour of a custom UIButton?

Upvotes: 3

Views: 914

Answers (2)

JAB
JAB

Reputation: 3235

If you want to do this in layoutSubviews, this will avoid the infinite loop you are currently creating:

- (void)layoutSubviews
{
    [super layoutSubviews];

    if (self.state == UIControlStateHighlighted) {
        self.titleLabel.textColor = [UIColor redColor];
    } else {
        self.titleLabel.textColor = [UIColor blueColor];
    }
}

Upvotes: 6

wattson12
wattson12

Reputation: 11174

Are you doing anything else with the UIButton subclass? If all you want to do is change the text colour you can use standard UIButton functionality:

[button setTitleColor:[UIColor redColor] forControlState:UIControlStateHighlighted];
[button setTitleColor:[UIColor whiteColor] forControlState:UIControlStateNormal];

Do this when setting up the button, it doesnt need to happen everytime layoutSubviews is called

Upvotes: 3

Related Questions