使用富文本解析html
2024-10-14 本文已影响0人
yuanweiphone
+ (NSMutableAttributedString *)formatText:(NSString *)text {
NSData* data = [text dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute :@(NSUTF8StringEncoding) };
NSError *error = nil;
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:&error];
if (error) {
NSLog(@"HTML 解析错误: %@", error);
return [[NSMutableAttributedString alloc] init];
}
// 创建可变富文本
NSMutableAttributedString *mutableAttributedString = [attributedString mutableCopy];
// 遍历整个富文本的范围,移除背景色属性
[mutableAttributedString enumerateAttribute:NSBackgroundColorAttributeName
inRange:NSMakeRange(0, mutableAttributedString.length)
options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (value) {
[mutableAttributedString removeAttribute:NSBackgroundColorAttributeName range:range];
}
}];
// 设置字体
[mutableAttributedString beginEditing];
[mutableAttributedString enumerateAttribute:NSFontAttributeName
inRange:NSMakeRange(0, mutableAttributedString.length)
options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (value) {
UIFont *newFont = [UIFont systemFontOfSize:14];
[mutableAttributedString addAttribute:NSFontAttributeName value:newFont range:range];
}
}];
[mutableAttributedString endEditing];
// 设置字体行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 1.5;
[mutableAttributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, attributedString.length)];
// 设置文本颜色
[mutableAttributedString enumerateAttribute:NSBackgroundColorAttributeName
inRange:NSMakeRange(0, mutableAttributedString.length)
options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
if (value) {
[mutableAttributedString removeAttribute:NSBackgroundColorAttributeName range:range];
}
}];
[mutableAttributedString addAttribute:NSForegroundColorAttributeName
value:hexColor(333333)
range:NSMakeRange(0, attributedString.length)];
return mutableAttributedString;
}