4

我有一个包含格式化文本和嵌入图像的 NSTextView,如下所示。

带有格式化文本和嵌入图像的 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 回答