zoukankan      html  css  js  c++  java
  • iOS图文存储的一种尝试

    想法基于 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];   //显示内容 

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

      

  • 相关阅读:
    javaday19_List接口_Set接口
    01玩转数据结构_04_最基础的动态数据结构:链表
    10 拖拽的对话框_滚动条_放大镜_
    01玩转数据结构_03_栈和队列
    java小技巧
    01玩转数据结构_02_不要小瞧数组
    01玩转数据结构_01_课程介绍
    javaday18_ArrayList
    JZOJ.3777【NOI2015模拟8.17】最短路(shortest)
    JZOJ.5230【NOIP2017模拟8.5】队伍统计
  • 原文地址:https://www.cnblogs.com/marks007/p/4681407.html
Copyright © 2011-2022 走看看