HTML标签 转 NSAttributedString
2018-03-12 本文已影响106人
CocoaJason
NSDictionary *options = @{
NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType
};
NSAttributedString *attributeString = [[NSAttributedString alloc] initWithData:[@"<font color = 'blue' size = '8'>改革开放</font> <font color = 'red' size = '30'>40</font>年" dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil];
NSRange range = NSMakeRange(0, attributeString.string.length);
NSMutableAttributedString *mutableAttributeString = [[NSMutableAttributedString alloc] initWithAttributedString:attributeString];
[attributeString enumerateAttributesInRange:range options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary<NSAttributedStringKey,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
UIFont *oldFont = [attrs objectForKey:NSFontAttributeName];
NSMutableDictionary *newattrs = [attrs mutableCopy];
[newattrs setValue:[UIFont systemFontOfSize:oldFont.pointSize] forKey:NSFontAttributeName];
[mutableAttributeString setAttributes:newattrs range:range];
}];