码迷,mamicode.com
首页 > 移动开发 > 详细

iOS图文存储的一种尝试

时间:2015-07-27 22:46:07      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

想法基于 iOS7 的 textkit 的基础!

由于 iOS7 将过去设计图文混排的方法打包到 textkit 当中,所以我们在 iOS7 系统下可以很简单的实现图文混排。

使用 NSAttributedString 来实现处理,将 NSAttributedString 转化为 NSData 再存储到文件里。

代码如下:

@property (weak, nonatomic) IBOutlet UITextView *input;    //文本输入框

@property (strong, nonatomic) NSMutableAttributedString * context;//存储图文

   _context = _input.textStorage;    //把文本输入框内容赋给存储

   NSString *imageName = @"1.jpg";

   UIImage *image = [UIImage imageNamed:imageName];//通过文件名加载图片,有缓存

   NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil]; //附件

   attachment.image = image;

   NSAttributedString *textattach = [NSAttributedString attributedStringWithAttachment:attachment];//附件转化为 NSAttributedString

   NSRange range = self.input.selectedRange;    //点击的位置,插入点

   NSInteger i = 0;

   i = range.location;

   [_content insertAttributedString:textattach atIndex:i];   //将图片插入

   NSString *path = [(NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)) objectAtIndex:0];  //获得沙箱的 Document 的地址
   NSString *pathFile = [path stringByAppendingPathComponent:@"text"];  //要保存的文件名

   NSData *data = [_context dataFromRange:NSMakeRange(0, _content.length) documentAttributes:@{NSDocumentTypeDocumentAttribute:NSRTFDTextDocumentType} error:nil];   //将 NSAttributedString 转为NSData

   [data writeToFile:pathFile atomically:YES];  //写入文件

 

 

  读取:

@property (weak, nonatomic) IBOutlet  UITextView *output;

  NSData *outputData = [NSData dataWithContentsOfFile:pathfile];

  NSAttributedString *temp = [[NSAttributedString alloc] initWithData:outputData options:@{NSDocumentTypeDocumentAttribute : NSRTFDTextDocumentType} documentAttributes:nil error:nil];     //读取

  [_output  setAttributedText:temp];   //显示内容 

注释:这里没考虑图片大小对显示的影响,建议设置大小在插入图片的时候

  

iOS图文存储的一种尝试

标签:

原文地址:http://www.cnblogs.com/marks007/p/4681407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!