0

我从服务器动态获取 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"

4

0 回答 0