在 iOS 7 中,我们获得了将 HTML 字符串转换为 NSAttributedString 的能力,如下所示:
NSString *html = @"<bold>Wow!</bold> Now <em>iOS</em> can create <h3>NSAttributedString</h3> from HTMLs!";
NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:nil];
我们还可以为未使用 NSDefaultAttributesDocumentAttribute 选项指定某些属性的 HTML 提供默认值。
我的问题是:有没有办法告诉 NSAttributedString 忽略它在 HTML 中看到的某些属性(例如颜色),而是使用我提供的属性?换句话说,我想提供一个覆盖属性值,而不是默认值。
最佳答案
您可以尝试枚举整个字符串。例如,尝试更改链接颜色。
NSMutableAttributedString *mttrString = [attrString mutableCopy];
[mutableString beginEditing];
[mutableString enumerateAttribute:NSLinkAttributeName
inRange:NSMakeRange(0, res.length)
options:0
usingBlock:^(id value, NSRange range, BOOL *stop) {
if (value) {
UIFont *oldFont = (UIFont *)value;
UIFont *newFont = [UIFont systemFontOfSize:12.f];
[res addAttribute:NSFontAttributeName value:newFont range:range];
}
}];
[res endEditing];
attrString = mAttrString;
我还没有尝试过,但你应该能够以这种方式操作字符串。
关于ios - 使用 NSAttributedString 覆盖 HTML 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28567322/