目标C-使用自己的样式从HTML文本更改属性字符串的字体

问题描述

我正在从服务器动态获取HTML字符串,并将其解析为属性字符串以在我的应用中显示。 由于字符串具有自己的样式,因此显示的字体和大小不同,这会影响我们的设计选择。

有些文本是用颜色定义的,有些则不是。

示例颜色定义:<b><font color="red">Sample Red Color</font></b>

我想为所有文本设置字体和大小,并仅为那些没有颜色定义的文本设置颜色。

这是我的代码

`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;`

这会更改所有字符串的颜色,我只想为那些未定义颜色的文本更改颜色。红色文本仍应为红色,其他文本应为@“ 454545”

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)