0

I am dynamically getting an HTML string from Server and parsing it to an Attributed String to show it in my app. Since the string has its own styles, it shows different fonts and sizes, something that is affecting our design choices.

Some text is color defined and some are not.

Sample color definiton: <b><font color="red">Sample Red Color</font></b>

I want to set font and size for all text and to set the color for only those texts which don't have color definition.

Here is my code:

`msgContent.textColor = [UIColor colorFromHexString: @"454545"];

msgContent.text = message.messageContents;
message.messageContents = [message.messageContents stringByReplacingOccurrencesOfString: 
@"\n" withString: @"</br>"];

NSAttributedString * attributedString = [[NSAttributedString alloc]
                                         initWithData: [message.messageContents 
                                         dataUsingEncoding: NSUnicodeStringEncoding]
                                         options: @{ NSDocumentTypeDocumentAttribute: 
                                         NSHTMLTextDocumentType }
                                         documentAttributes: nil
                                         error: nil
    ];

if ([attributedString.string containsString: @"\n"]) {
}

UIColor *color =  [UIColor colorFromHexString: @"454545"];
NSDictionary *attrs = @{ NSForegroundColorAttributeName : color };

NSMutableAttributedString *newString = [[NSMutableAttributedString alloc] 
initWithAttributedString:attributedString];

NSRange range = (NSRange){0,[newString length]};

[newString enumerateAttribute:NSFontAttributeName inRange:range 
 options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id 
 value, NSRange range, BOOL *stop) {

    UIFont *contentFont =  [UIFont fontWithName: @"NotoSansCJKjp-Regular" size:14.0];
    [newString addAttribute:NSFontAttributeName value:contentFont range:range];
    [newString addAttributes:attrs range:range];

}];

msgContent.attributedText = newString;`

This changes color for all string, I want to change color only for those texts which don't have color defined. The Red color text should still be red, other text should be @"454545".

  • You have to call also `enumerateAttribute` looking for the color, and change the color if needed there. But don't you want to replace all the font style and size with the same one? If that's the case, then the iteration on `NSFontAttributeName` shouldn't be done, it's useless, you should set it in `attrs`. – Larme Oct 20 '20 at 07:40
  • Thanks for your comment. But somehow `NSFontAttributeName` worked for me to change the font and size of the text! I only have problem with the text color as described above. – Fazle Rabbi Linkon Oct 20 '20 at 10:29
  • This should be enough: https://pastebin.com/30cf5qS3 – Larme Oct 20 '20 at 14:26

0 Answers0