// 将HTML字符串转换为 NSAttributedString 的方法
- (NSAttributedString *)attributedStringFromHTMLString:(NSString *)htmlString {
NSError *error = nil;
NSAttributedString *initialAttrString = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
documentAttributes:nil
error:&error];
if (error) {
NSLog(@"Error converting HTML to NSAttributedString: %@", error.localizedDescription);
return nil;
}
NSMutableAttributedString *mutableAttrString = initialAttrString.mutableCopy;
// 设置全局字体大小(20px)
UIFont *font = [UIFont systemFontOfSize:14.0]; // 注意这里的20.0对应的是点数而不是像素
[mutableAttrString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, mutableAttrString.length)];
// 设置全局颜色为红色
UIColor *redColor = RGB(51, 51, 51);
[mutableAttrString addAttribute:NSForegroundColorAttributeName value:redColor range:NSMakeRange(0, mutableAttrString.length)];
return mutableAttrString;
}
网友评论