[英]HTML to NSAttributedString and NSAttributedString to HTML
[英]Use NSAttributedString to overwrite HTML attributes
在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;
我沒有嘗試過,但是您應該能夠以這種方式操作字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.