Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot change UIButton title after setAttributedTitle for it

I have an UIButton, I want to make color for a part of UIButton title so I create NSMutableAttributedString then setAttributedTitle for button.

After that, the color work fine but I can not change the title of UIButton

If I don't use setAttributedTitle (by comment the line [self.btnFanLevel setAttributedTitle:text forState:UIControlStateNormal]);), the UIButton title can change

Here is the function that I use to change UIButton title color and text

-(void)changeFanLevel: (NSString *) fanLevelTitle withColor:(UIColor *) color{
    NSLog(@"fanLevelTitle = %@", fanLevelTitle);
    [self.btnFanLevel setTitle:fanLevelTitle forState:UIControlStateNormal];

    NSMutableAttributedString *text =
    [[NSMutableAttributedString alloc]
     initWithAttributedString: self.btnFanLevel.titleLabel.attributedText];

    NSLog(@"text = %@", self.btnFanLevel.titleLabel.attributedText);

    [text addAttribute:NSForegroundColorAttributeName
                 value:color
                 range:NSMakeRange(10, 3)];

    [self.btnFanLevel setAttributedTitle:text forState:UIControlStateNormal];
}

Did I make something wrong? Any help would be appreciated.

UPDATE
I solve my problem by add this line before I set title for UIButton

[self.btnFanLevel setAttributedTitle:nil forState:UIControlStateNormal];

like image 886
Linh Avatar asked Mar 14 '23 18:03

Linh


1 Answers

The attributedTitle for any given controlState overrides the title for that controlState. So once you have set an attributedTitle for UIControlStateNormal (for example) then setTitle will not appear to make any change for that controlState unless you set the attributedTitle for that controlState to nil.

like image 180
Jef Avatar answered Apr 05 '23 23:04

Jef