11

HTMLを属性付きの文字列に変換するのではなく、HTMLに戻す必要があります。これは、Macで簡単に実行できます。http://www.justria.com/2011/01/18/how-to-convert-nsattributedstring-to-html-markup/

残念ながら、このメソッドdataFromRange:documentAttributes:はMacでAppKitAdditionsを介してのみ利用できますNSAttributedString

私の質問は、iOSでこれをどのように行うことができるかということです。

4

2 に答える 2

7

「簡単な」方法ではありませんが、次を使用して文字列の属性を反復処理するのはどうでしょうか。

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

NSMutableStringHTMLを蓄積するための変数があります(「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

それはあなたが望むことをするように見えます。

于 2011-07-04T01:42:02.653 に答える
1

以下のコードを使用してください。それはうまくいきます。

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];
于 2016-07-21T05:37:47.883 に答える