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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With