简体   繁体   中英

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

I am writing a Text Editor, with which users can input text with styles and insert images, so I am using NSAttributedString to manage the contents. My question is how can I store the contents before Text Editor was closed, and restore the contents after editor opened next time?

I wrote a category of NSAttributedString, right now I can store(and restore) text but not UIImageView in NSTextAttachment, below is part of my code:

-(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;

}

I had spent quite some time investigating and experimenting, and searches showed several people who had the same question, but no satisfactory answers.

最后,我使用了一个名为YYTextArchiver的 NSKeyedArchiver 子类来直接序列化 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM