簡體   English   中英

來自 NSAttributedString 的 HTML

[英]HTML from NSAttributedString

我不需要將 HTML 轉換為屬性字符串,而是將其轉換回 HTML。 這可以在 Mac 上輕松完成,如下所示: http://www.justria.com/2011/01/18/how-to-convert-nsattributedstring-to-html-markup/

不幸的是,方法dataFromRange:documentAttributes:僅在 Mac 上通過NSAttributedString AppKit Additions 可用。

我的問題是如何在 iOS 上做到這一點?

不是“簡單”的方式,而是如何使用以下方法遍歷字符串的屬性:

- (void)enumerateAttributesInRange:(NSRange)enumerationRange 
                           options:(NSAttributedStringEnumerationOptions)opts 
                        usingBlock:(void (^)(NSDictionary *attrs, NSRange range, BOOL *stop))block

有一個NSMutableString變量來累積 HTML(我們稱之為“html”)。 在該塊中,您將使用字符串手動構造 HTML。 例如,如果文本屬性 'attrs' 指定紅色粗體文本:

[html appendFormat:@"<span style='color:red; font-weight: bold;'>%@</span>", [originalStr substringWithRange:range]]


編輯:昨天偶然發現:

來自“UliKit”的 NSAttributedString+HTMLFromRange 類別( https://github.com/uliwitness/UliKit/blob/master/NSAttributedString+HTMLFromRange.m

看起來它會做你想做的事。

使用下面的代碼。 它運作良好。

NSAttributedString *s = ...;
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute:    NSHTMLTextDocumentType};    
NSData *htmlData = [s dataFromRange:NSMakeRange(0, s.length)    documentAttributes:documentAttributes error:NULL];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM