ios - 使用 NSAttributedString 覆盖 HTML 属性

标签 ios nsattributedstring

在 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/

相关文章:

ios - Storyboard中带有自定义字体的属性字符串无法正确加载

ios - 如何调整图像大小或作为 NSAttributedString NSTextAttachment 完成(或设置其初始大小)

ios - UITextView 延迟滚动添加图像

ios - UITextView 末尾的额外空间

ios - 如何使用 NSUnderlineStyle.PatternDot

ios - 以编程方式调整 safeArea 的 collectionView

ios - 延迟加载 UIScrollView 或 UITableView

objective-c - iOS/越狱上的 tcpdump

ios - 渲染到纹理与渲染到 CAEAGLLayer 支持的 View ?

ios - 在 iOS 中保持应用程序空闲一段时间后,SRWebsocket 连接自动关闭