Search code examples
iosobjective-cnsattributedstring

Change color and size portion of NSString with NSMutableAttributedString


Browsed through a few NSAttributedString examples but can't seem to get this working. I am trying to change the size and color of part of a NSMutableAttributedString.

I've tried a few variations of this:

NSMutableAttributedString *hintText = [[NSMutableAttributedString alloc] initWithString:@"This is red and huge and this is not"];

//Black and large
[hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:20.0f], NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(0, 11)];

//Rest of text -- just futura
[hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:16.0f]} range:NSMakeRange(12, ((hintText.length -1) - 12))];

This just changes the size of the text, not the color. Can someone point me in the right direction?

EDIT: I use this like so: myUILabel.attributedText = hintText;


Solution

  • When I'm trying to do something like this, I find it to be easier to build individual pieces (each of which is an NSAttributedString) and then "glue" them together with something like the following:

    NSAttributedString *string1 = // Get the red and large string here
    NSAttributedString *string2 = // Get the just futura string here
    
    NSMutableAttributedString *hintText = [[NSMutableAttributedString alloc] init];
    [hintText appendAttributedString:string1];
    [hintText appendAttributedString:string2];
    

    I find this makes it much easier to follow the logical flow and I've never found this way to have performance limitations that needed optimization.


    Update:

    FWIW, I got the following code to work as I believe the OP desires:

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
        NSMutableAttributedString *hintText = [[NSMutableAttributedString alloc] initWithString:@"This is red and huge and this is not"];
    
        //Red and large
        [hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:20.0f], NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(0, 20)];
    
        //Rest of text -- just futura
        [hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:16.0f]} range:NSMakeRange(20, hintText.length - 20)];
    
        [self.button setAttributedTitle:hintText forState:UIControlStateNormal];
    
    }
    

    Note that he was specifying [UIColor blackColor] and I updated that to [UIColor redColor]. Also, I updated the range calculations to include all of the characters in "This is red and huge".