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];   //显示内容 

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

      

  • 相关阅读:
    JS动态添加事件
    Asp.Net验证控件浅析
    word 文档如何加密
    scp 自动带密码参数复制文件到主机
    Zabbix监控Dell服务器相关硬件资源
    Zabbix的history相关数据表数据太大,执行表分区操作过程
    mysql日常操作
    linux下利用tcpdump抓包工具排查nginx获取客户端真实IP实例
    解决ssh登录很慢的问题以及jumpserver登录主机出现:Authentication timeout
    keepalived启动后报错:(VI_1): received an invalid passwd!的解决办法
  • 原文地址:https://www.cnblogs.com/marks007/p/4681407.html
Copyright © 2011-2022 走看看