仅使用粗体和斜体将 NSAttributedString 转换为 HTML

Convert NSAttributedString to HTML with only bold and italics

我希望将 NSAttributedString 转换为 HTML,但只保留粗体和斜体属性。我不关心字体系列、字体大小或类似的东西。

我基本上是想转换: 猎鹰

<b>Go</b> <em>Falcons</em>

有办法吗?

我不确定这是否是一个可行的解决方案,但一种方法是枚举属性并遍历每个部分并制作您自己的 HTML。

 [str enumerateAttribute:NSFontAttributeName
                inRange:range
                options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
             usingBlock:^(id value, NSRange range, BOOL *stop) {
               UIFont *currentFont = value;
               if ([currentFont.fontName rangeOfString:@"bold" options:NSCaseInsensitiveSearch]
                       .location != NSNotFound) {
                   //Do something with the string and range for bold? add tags and append in a different string
               } 
               // Similarly do something for for non-bold, itatlic or normal text. Keep Appending them in a string
             }];