Search code examples
iosobjective-cnsstringnsattributedstring

iOS: how to change colour/font of some characters of a string


in my app i have to change the font of a part of string which comes from JSON response

> "<span class=\"drop_data_user\">Andrew James</span> liked your comment
> \"hiiiiiiiiiiiiiii\" that you posted."

to convert it in attributed string i am using the following code

NSAttributedString *attr = [[NSAttributedString alloc] initWithData:[NotificationTxt dataUsingEncoding:NSUTF8StringEncoding]
                                                                options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                          NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)}
                                                     documentAttributes:nil
                                                                  error:nil];

I want to change the font colour of the sender


Solution

  • NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString:@"My String"];
    [attrS addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 2)];
    [attrS addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(3, 6)];
    
    self.myLabel.attributedText = attrS;
    

    For fonts use

    [attrS addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, 3)];