nstextview - 如何在 cocoa 中将 NSTextView RTFD 数据转换为纯文本

标签 nstextview nsattributedstring string-conversion

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

NSTextView with formatted text and embedded image

我想将上面转换为纯文本,如下所示:

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

谢谢

最佳答案

尝试了几个小时后,我根据自己的要求提出了以下解决方案。请告诉我我们是否有更好的方法来做到这一点。

我使用以下代码创建了 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。

关于nstextview - 如何在 cocoa 中将 NSTextView RTFD 数据转换为纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6516052/

相关文章:

swift - 如何让NSTextView的高度一直高于实际高度20px?

ios - 当辅助功能打开时,无法打开 UITextView(属性文本)内的 NSURL

sql-server - 如何检查 VARCHAR 字符串是否(不是)十六进制?

iphone - 在 iOS 中将 HTML 转换为 NSAttributedString

ios - NSMutableAttributedString 是否自动连接相同的相邻属性?

c# - 将int转换为一定长度的char的字符串

java - 尝试解析字符串时出现数字格式异常

objective-c - 如何使 Tab 键将焦点移出 NSTextView?

swift - 检测到 NSTextView 缺少约束

objective-c - 缩放预览: use NSTextView, NSTextField、CATextLayer 或drawInRect?