4

次のような書式設定されたテキストと埋め込み画像を含む NSTextView が1つあります。

書式設定されたテキストと埋め込み画像を含む NSTextView

上記を次のようなプレーンテキストに変換したい:

Hi this is test data (...picture...)This is colored text.

ありがとう

4

1 に答える 1

4

数時間試した後、私は自分の要件に対して次の解決策を思いつきました.それを行うためのより良い方法があるかどうか教えてください.

次のコードで NSString カテゴリを作成しました。

+ (NSString *)plainTextFromRTFD:(NSTextStorage *)aTextStorage 
           attachmentString:(NSString *)aString {

NSString *returnString = @"";

//Default value of aString, If nil
if (aString == nil) {
    aString = @"(...Attachment...)";
}

if (aTextStorage && aString) {

    //Initialize NSMutableString object to hold plain text
    NSMutableString *plainText = [[NSMutableString alloc] init];

    //Loop through all the attributes one-by-one to identify the NSAttachment
    for(int i =0;i<[aTextStorage length];i++) {

        NSDictionary *attr= [aTextStorage attributesAtIndex:i effectiveRange:NULL];

        //Check whether attribute contains NSAttachment or not
        if ([attr objectForKey:@"NSAttachment"] != nil) {
            //Replace NSTextAttachment with attachmentString value
            [plainText appendFormat:@"%@",aString];
        } else {
            //Add character to plain text
            [plainText appendFormat:@"%@",[[[aTextStorage characters] objectAtIndex:i] string]];    
        }
    }

    //copy NSString from NSMutableString
    returnString = [plainText copy];

    //release NSMutableString
    [plainText release];
}

return [returnString stringByReplacingOccurrencesOfString:@"\n" withString:@" "];}

そして、私は次のように使用しています:

NSLog(@"%@",[NSString plainTextFromRTFD:[contentView textStorage] attachmentString:nil]);

contentView は NSTextView です。

于 2011-06-29T07:02:55.393 に答える