当前位置: 移动技术网 > IT编程>移动开发>IOS > iOS实现富文本编辑器的方法详解

iOS实现富文本编辑器的方法详解

2019年07月24日  | 移动技术网IT编程  | 我要评论

喧哗番长2,金三角坤沙玩的女人,油价迎新年首次下调

前言

富文本编辑器不同于文本编辑器,国内做的比较好的比如有百度的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;
}

总结

好了,至此可实现一个富文本编辑器的新增与编辑。以上就是本文的全部内容,希望对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网