iOS實現富文字編輯器的方法詳解_IOS

來源:互聯網
上載者:User

前言

富文字編輯器不同於文字編輯器,國內做的比較好的比如有百度的UEditor和kindEditor。但是這兩個也有它的缺點:介面過於複雜、不夠簡潔、UI設計也比較落後、不夠輕量化,這篇文章我們將給大家介紹利用iOS如何?富文字編輯器。

實現的效果

解決思路

採用webview載入一個本地html檔案,該html內部編寫好js方法用於與oc相互調用 最終輸出該富文本字串傳輸給伺服器

為什麼選擇這樣的方式

服務端要求我最終返回的資料格式為:

{ @"Id":"當時建立模板這個不傳,更新模板必須傳", @"title":"模板標題", @"text":"<p dir="ltr">測試文字</p>![](http://upload-images.jianshu.io/upload_images/1694866-a9a1da57455b2054.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)<p>![](http://pic.baikemy.net/apps/kanghubang/486/3486/1457968327238.amr@type=1@duration=1852)<p>", @"sendstr":"22372447516929 如果模板要儲存同時發送給患者,這個值必須傳,可以多個患者發送患者id以逗號隔開" @"1457968280769.jpg": @"檔案名稱":"BACES64 資料 這個是多個圖片或語音一起上傳"}

其中text欄位即為富文字欄位.

同時又需要編輯已有文本等功能.倘若用原生代碼寫較為複雜,最終選擇了使用本地html代碼實現

解決步驟

建立一個richTextEditor.html檔案

1.頁面設計

/*介面不要太簡單 一個簡單的輸入框*/ <style>  img   {   display: block;   width: 100%;   margin-top: 10px;   margin-bottom: 10px;   }  [contenteditable=true]:empty:before  {   content: attr(placeholder);   color: #a6a6a6;  }  #content   {   padding: 10px 0;   font-family:Helvetica;   -webkit-tap-highlight-color: rgba(0,0,0,0);   min-height:100px;   }<div id="content" contenteditable="true" onmouseup="saveSelection();" onkeyup="saveSelection();" onfocus="restoreSelection();" placeholder="輕觸螢幕開始編輯本文" ></div>

2.js方法設計

插入圖片

 function insertImage(imageName, imagePath) {  restoreSelection();  var imageElement = document.createElement('img');  var breakElement = document.createElement('div');  imageElement.setAttribute('src', imagePath);  imageElement.setAttribute('id', imageName);  breakElement.innerHTML = "<br>";  editableContent.appendChild(imageElement);  editableContent.appendChild(breakElement); } function updateImageURL(imageName, imageURL) {  var selectedElement = document.getElementById(imageName);  selectedElement.setAttribute('src', imageURL); }

擷取html代碼

function placeHTMLToEditor(html){  editableContent.innerHTML = html;}

4.oc與js相互調用

oc端執行個體一個webview載入該html和一個按鈕用於添加圖片

  self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64+50, [UIScreen mainScreen].bounds.size.width, self.view.frame.size.height - 50)];  self.webView.delegate = self;  [self.view addSubview:self.webView];  NSBundle *bundle = [NSBundle mainBundle];  NSURL *indexFileURL = [bundle URLForResource:@"richTextEditor" withExtension:@"html"];  [self.webView setKeyboardDisplayRequiresUserAction:NO];  [self.webView loadRequest:[NSURLRequest requestWithURL:indexFileURL]];  UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];  [btn addTarget:self action:@selector(addImage:) forControlEvents:UIControlEventTouchUpInside];  [self.view addSubview:btn];

添加完圖片後與html對接

 //以時間戳記重新命名圖片  NSString *imageName = [NSString stringWithFormat:@"iOS%@.jpg", [self stringFromDate:[NSDate date]]];  NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:imageName];  NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];  UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];  NSInteger userid = [[NSString stringWithFormat:@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"userID"]] integerValue];  NSString *url = [NSString stringWithFormat:@"http://pic.baikemy.net/apps/kanghubang/%@/%@/%@",[NSString stringWithFormat:@"%ld",userid%1000],[NSString stringWithFormat:@"%ld",(long)userid ],imageName];  NSString *script = [NSString stringWithFormat:@"window.insertImage('%@', '%@')", url, imagePath];  NSDictionary *dic = @{@"url":url,@"image":image,@"name":imageName};  [_imageArr addObject:dic];//全域數組用於儲存加上的圖片  [self.webView stringByEvaluatingJavaScriptFromString:script];

編輯完成後拿出html代碼

  NSString *html = [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('content').innerHTML"];

編輯服務器中的富文本

   NSString *place = [NSString stringWithFormat:@"window.placeHTMLToEditor('%@')",self.inHtmlString];   [webView stringByEvaluatingJavaScriptFromString:place];

5.與服務端對接

此時我們取出的富文本如下:

企鵝的時候要[站外圖片上傳中……(4)]<div>阿空間裡發紅包啦?我</div>[站外圖片上傳中……(5)]<div><br></div>

其中id部分為我處理的特殊部分

處理方法如下

-(NSString *)changeString:(NSString *)str{    NSMutableArray * marr = [NSMutableArray arrayWithArray:[str componentsSeparatedByString:@"\""]];  for (int i = 0; i < marr.count; i++)  {    NSString * subStr = marr[i];    if ([subStr hasPrefix:@"/var"] || [subStr hasPrefix:@" id="])    {      [marr removeObject:subStr];      i --;    }  }  NSString * newStr = [marr componentsJoinedByString:@"\""];  return newStr;}

總結

好了,至此可實現一個富文字編輯器的新增與編輯。以上就是本文的全部內容,希望對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.