user4951
user4951

Reputation: 33050

Better Way to Set Button Title for 2 States

This is how I am doing it now

[self.distanceFilter setTitle:strValueForDistanceFilter forState:UIControlStateNormal];
[self.distanceFilter setTitle:strValueForDistanceFilter forState:UIControlStateSelected];

What would be a better way to do so, so that the title change for bot UIControlStateNormal and even if the button is selected

What I've tried:

[self.distanceFilter setTitle:strValueForDistanceFilter forState:UIControlStateNormal | UIControlStateSelected];

The thing is UIControlStateNormal is 0. So UIControlStateNormal | UIControlStateSelected is just UIControlStateSelected. That means the title don't change when button is not selected.

Upvotes: 0

Views: 126

Answers (3)

Cyrille
Cyrille

Reputation: 25144

Well, that sounds like a perfect job for a category on UIButton:

- (void)setTitleForAllStates:(NSString *)title
{
    for (UIControlState i = 0; i <= 3; i++)
        [self setTitle:title forState:i];
}

Upvotes: 2

Hemang
Hemang

Reputation: 27050

Some other way,

#define UIControlStateAll UIControlStateNormal | UIControlStateSelected | UIControlStateHighlighted

[self.distanceFilter setTitle:strValueForDistanceFilter forState:UIControlStateAll];

Upvotes: 1

Simon McLoughlin
Simon McLoughlin

Reputation: 8465

You can use an | to perform a bitwsie OR, Like so:

[self.distanceFilter setTitle:strValueForDistanceFilter forState:UIControlStateNormal | UIControlStateSelected];

Upvotes: 3

Related Questions