Set UIButton header with a single method call?

I would like to set the UIButton header through code. I need to call - [UIButton setTitle: forState:] for UIControlStateNormal, UIControlStateHighlighted, UIControlStateDisabled, UIControlStateSelected. And this does not even take into account all combinations of these states together.

Needless to say, this is tiring. Is there one call I can make that sets one line as a header for all states? (Since, I believe, in 95% of cases this is the desired behavior?)

+3
source share
4 answers

Yes of course. From the docs :

, , UIControlStateNormal. UIControlStateNormal , . , .

, UIControlStateNormal .

+9

-. , UIControlStateNormal . - . UIControlState - , , :

[button setTitle:@"Title" forState:UIControlStateNormal|UIControlStateHighlighted| UIControlStateDisabled|UIControlStateSelected]

:

#define kAllControlStates (UIControlStateNormal|UIControlStateHighlighted| UIControlStateDisabled|UIControlStateSelected)
[button setTitle:@"Title" forState:kAllControlStates];

:

[button setTitle:@"Title" forState:0xffff];

. . , UIControlStateHighlighted|UIControlStateDisabled , . , " ". , .

+7

UIButton, .

0

UIControlStateNormal, , 99% , 1%. ( , , .)

, . , .

@interface UIButton (AdditionalStates)
- (void)setTitle:(NSString *)title forState:(UIControlState)state additionalStates:(UIControlState)additionalStates;
@end

@implementation UIButton (AdditionalStates)

- (void)setTitle:(NSString *)title forState:(UIControlState)state additionalStates:(UIControlState)additionalStates
{
    [self setValue:title forKey:@"title" state:state additionalStates:additionalStates mask:(1 << 0)];
}

- (void)setValue:(id)value forKey:(NSString *)key state:(UIControlState)state additionalStates:(UIControlState)additionalStates mask:(NSUInteger)mask(UIControlState)additionalStates
{
    if (additionalStates == 0) {
        [self setValue:value forKey:key state:state];
        return;
    }

    // Iterate over each 'on' bit in additionalStates, starting from the mask bit
    while (mask > 0) {
        if (additionalStates & mask) {
            // Delete the current bit from additionalStates
            NSUInteger reducedAdditionalStates = (additionalStates ^ mask);

            // Set the title for combinations of the remaining additional states with and without the mask bit
            [self setValue:value forKey:key state:(state | (additionalStates & mask)) additionalStates:reducedAdditionalStates mask:(mask << 1)];
            [self setValue:value forKey:key state:state additionalStates:reducedAdditionalStates mask:(mask << 1)];
        }
        mask = (mask << 1);
    }
}

- (void)setValue:(id)value forKey:(NSString *)key state:(UIControlState)state
{
    if ([key isEqualToString:@"title"]) {
        [self setTitle:value forState:state];
        return;
    }
}

@end
0

Source: https://habr.com/ru/post/1737720/


All Articles