gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:07:10 27 4
gpt4 key购买 nike

我正在编写一个文本编辑器,用户可以使用它输入带有样式的文本并插入图像,所以我使用 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;

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

最佳答案

最后,我使用了 NSKeyedArchiver 的一个子类,名为 YYTextArchiver直接序列化 NSAttributedString,它对我有用。

关于ios - 可以存储(或恢复)包含 NSTextAttachment 的 NSAttributedString 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36465761/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com