iOS圖文儲存的一種嘗試

來源:互聯網
上載者:User

標籤:

想法基於 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圖文儲存的一種嘗試

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.