Search code examples
iosobjective-cnsattributedstring

Display string having words with multiple formatting


In my app, I am displaying user comment that is fetched from the server. The comment contains user name, tag and some text in bold.

For example: "Nancy tagged Clothing: Season 2, Episode 5. where do they find all the old clothes"

The words "Nancy" and "Clothing:" should be gray and orange color, respectively and "Season 2, Episode 5." should be bold.

I have tried using NSAttributedString but failed to achieve the above.

Following is the code I tried to change color but nothing changed. I am not very sure of how to use NSAttributedString.

NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:", tag.title]];
    [title addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:246/255.0 green:139/255.0 blue:5/255.0 alpha:1.0f] range:NSMakeRange(0,[title length])];
    self.tagCommentLabel.text = [NSString stringWithFormat:@"%@ tagged %@: %@ %@",tag.user.name , title, episode, tag.comment];

Can someone help me with a code as to how can I achieve the example sentence with the desired formatting?


Solution

  • NSAttributedString and NSString are two different things. If you want to add attributes to NSString (e.g. change the color of the text), you have to first make the NSString:

    NSString *string = [NSString stringWithFormat:@"%@ tagged %@: %@ %@",tag.user.name , title, episode, tag.comment];
    

    Then you make NSMutableAttributedString from your NSString and add attributes to it:

    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:string]; 
    [attString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:246/255.0 green:139/255.0 blue:5/255.0 alpha:1.0f] range:[string rangeOfString:title];
    

    And when you want to display your attributed string, you should use .attributedText instead of .text:

    self.tagCommentLabel.attributedText = attString;