NSMutableString不适用于HTML文本

时间:2016-02-03 06:39:32

标签: ios objective-c nsmutableattributedstring

代码工作正常..所有HTML标签也已实现但当我设置字体和颜色等属性时,HTML字符串转换为普通字符串..

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;

2 个答案:

答案 0 :(得分:2)

是的,由于某种原因,HTML NSAttributedString无法使用属性,但我可以使用html字符串设置字体和颜色,如下所示:

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

答案 1 :(得分:1)

您必须使用更新的字体和颜色值更新NSMutableAttributedString中的所有范围。 使用此修改后的代码:

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;