Balaji Gupta
Balaji Gupta

Reputation: 33

NSMutableString is not working for HTML Text

Code is working fine..all the HTML tags also implemented but when i set attributes like font and color the HTML string convert into normal string..

NSString * htmlString = [NSString stringWithFormat:@"<html><div>%@</div></html>",_strAchievementMsg];

NSDictionary *attrDict = @{ NSFontAttributeName : [UIFont fontWithName:HelveticaNeue size:11.0f],
NSForegroundColorAttributeName :[UIColor colorWithRed:105.0f/255.0f green:115.0f/255.0f blue:144.0f/255.0f alpha:1.0f]
                                           };
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
[attrStr addAttributes:attrDict range:NSMakeRange(0,attrStr.length)];
_strAchievementAttributed = attrStr;

Upvotes: 0

Views: 561

Answers (2)

Aruna Mudnoor
Aruna Mudnoor

Reputation: 4825

You have to update all the ranges in the NSMutableAttributedString with updated font and color values. Use this modified code:

NSString * htmlString = [NSString stringWithFormat:@"<html><div>%@</div></html>",_strAchievementMsg];

NSDictionary *attrDict = @{ NSFontAttributeName : [UIFont fontWithName:HelveticaNeue size:11.0f],
                            NSForegroundColorAttributeName :[UIColor colorWithRed:105.0f/255.0f green:115.0f/255.0f blue:144.0f/255.0f alpha:1.0f]
                            };
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];

NSMutableAttributedString * updatedAttrStr = [[NSMutableAttributedString alloc] initWithAttributedString:attrStr];

[attrStr enumerateAttributesInRange:NSMakeRange(0, attrStr.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
    [updatedAttrStr addAttributes:attrDict range:range];
}];
_strAchievementAttributed = updatedAttrStr;

Upvotes: 1

null
null

Reputation: 1178

ya i had the same problem for some reason HTML NSAttributedString does not work with attributes but you can set the font and color using the html string like this:

NSString * htmlString = [NSString stringWithFormat:@"<html><div style='color:#697390; font-size:11px; font-family:HelveticaNeue;'>%@</div></html>",_strAchievementMsg];

Upvotes: 3

Related Questions