NSMutableString 不适用于 HTML 文本

NSMutableString is not working for HTML Text

代码工作正常..所有 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;

是的,出于某种原因我遇到了同样的问题 HTML NSAttributedString 不适用于属性,但您可以使用 html 字符串设置字体和颜色,如下所示:

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

您必须使用更新的字体和颜色值更新 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;