可以存储(或恢复)包含 NSTextAttachment 的 NSAttributedString 吗?

Can NSAttributedString which contains NSTextAttachment be stored(or restored)?

我正在编写一个文本编辑器,用户可以使用它输入带有样式的文本并插入图像,所以我使用 NSAttributedString 来管理内容。我的问题是如何保存文本编辑器关闭前的内容,并在下次编辑器打开后恢复内容?

我写了一个类NSAttributedString,现在我可以在NSTextAttachment中存储(和恢复)文本但不能存储UIImageView,下面是我的部分代码:

-(NSData*)customEncode {
__block NSMutableArray* archivableAttributes=[[NSMutableArray alloc]init];

[self enumerateAttributesInRange:NSMakeRange(0, [self length]) options:0 usingBlock:^(NSDictionary *attrs, NSRange range, BOOL *stop) {
    NSLog(@"range: %d %d",range.location, range.length);
    NSLog(@"dict: %@",attrs);
    NSLog(@"keys: %@", [attrs allKeys]);
    NSLog(@"values: %@", [attrs allValues]);

    NSMutableDictionary* tDict=[[NSMutableDictionary alloc]init];

    [tDict setObject:[NSNumber numberWithInt:range.location] forKey:@"location"];
    [tDict setObject:[NSNumber numberWithInt:range.length] forKey:@"length"];

    for (NSString* tKey in [attrs allKeys]) {
        if ([tKey isEqualToString:@"CTUnderlineColor"]) {
            [tDict setObject:[NSAttributedString arrayFromCGColorComponents:((CGColorRef)[attrs objectForKey:@"CTUnderlineColor"])] forKey:@"CTUnderlineColor"];
        }
        if ([tKey isEqualToString:@"NSUnderline"]) {
            NSNumber* underline=[attrs objectForKey:@"NSUnderline"];
            [tDict setObject:underline forKey:@"NSUnderline"];
        }
        if ([tKey isEqualToString:@"CTForegroundColor"]) {
            [tDict setObject:[NSAttributedString arrayFromCGColorComponents:((CGColorRef)[attrs objectForKey:@"CTForegroundColor"])] forKey:@"CTForegroundColor"];
        }
        if ([tKey isEqualToString:@"NSFont"]) {
            CTFontRef font=((__bridge CTFontRef)[attrs objectForKey:@"NSFont"]);

            NSDictionary* fontDict=[NSDictionary
                                    dictionaryWithObjects:
                                    [NSArray arrayWithObjects:(NSString*)CFBridgingRelease(CTFontCopyPostScriptName(font)),[NSNumber numberWithFloat:CTFontGetSize(font)], nil]
                                    forKeys:
                                    [NSArray arrayWithObjects:@"fontName", @"fontSize", nil]];

            [tDict setObject:fontDict forKey:@"NSFont"];
        }
    }

    [archivableAttributes addObject:tDict];
}];

NSMutableDictionary* archiveNSMString=[NSMutableDictionary
                                       dictionaryWithObjects: [NSArray arrayWithObjects:[self string],archivableAttributes,nil]
                                       forKeys:[NSArray arrayWithObjects:@"string",@"attributes",nil]];

NSLog(@"archivableAttributes array: %@",archiveNSMString);

NSData* tData=[NSKeyedArchiver archivedDataWithRootObject:archiveNSMString];

NSLog(@"tdata: %@",tData);

return tData;

}

我花了很多时间调查和试验,搜索显示有几个人有同样的问题,但没有满意的答案。

使用 fileWrapperFromRange:documentAttributes:error: 文档类型 NSRTFDTextDocumentType

最后,我使用了NSKeyedArchiver的子类YYTextArchiver直接序列化了NSAttributedString,对我有用

//Swift-3
You can store NSTextAttachment images by :-

var imageArray : [UIImage]


//MARKS:-  Extract attachedImage
    func textViewDidChange(_ textView: UITextView)  {
        imageArray = [UIImage]()
        let range = NSRange(location: 0, length: textView.attributedText.length)
        if (textView.textStorage.containsAttachments(in: range)) {
            let attrString = textView.attributedText
            var location = 0
            while location < range.length {
                var r = NSRange()
                let attrDictionary = attrString?.attributes(at: location, effectiveRange: &r)
                if attrDictionary != nil {
                    let attachment = attrDictionary![NSAttachmentAttributeName] as? NSTextAttachment
                    if attachment != nil {
                        if attachment!.image != nil {
                          //store the image Attached to it.
                          imageArray.append( attachment!.image!)
                        }
                    }
                    location += r.length
                }
            }
        }
    }

}

Concat all the above image Attached to it :-

let axtractedImageAttribute = NSMutableAttributedString()
        for image in imageArray {
            let attachment:NSTextAttachment = NSTextAttachment()
            attachment.image = image
            attachment.setImageHeight(height: 20)
            let attachmentString:NSAttributedString = NSAttributedString(attachment: attachment)
            axtractedImageAttribute.append(attachmentString)
        }

Demo