A detailed approach to implementing a rich text editor in IOS _ios

Source: Internet
Author: User

Objective

Rich Text Editor is different from the text editor, the domestic do relatively good such as Baidu's Ueditor and Kindeditor. But these two also have its disadvantage: the interface is too complex, not concise, UI design is also relatively backward, not lightweight, this article we will introduce how to use iOS to implement Rich text editor.

Effect of implementation

Solving ideas

Using WebView to load a local HTML file, the HTML internally written a good JS method for interacting with OC to call the final output of the rich text string transmitted to the server

Why choose such a way

The service side requires me to eventually return the data in the format:

{
 @ "Id": "The new template this does not pass, update template must pass",
 @ "title": "Template title",
 @ "text": "<p dir=" ltr "> Test text </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 if the template is to be saved at the same time to send to the patient, this value must be passed, can be multiple patients send patient IDs separated by commas "
 @" 1457968280769.jpg ":
 @" filename ":" BACES64 Data this is uploaded with multiple pictures or sounds "
}

Where the text field is a rich text field.

At the same time, you need to edit the existing text and other functions. If the native code is more complex to write, the final choice is to use local HTML code to implement

Resolution Steps

Create a new richtexteditor.html file

1. Page Design

/* Interface not too simple a simple input box * *
 <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=" touch screen start edit Body "></div>

2.js Method Design

Insert Picture

 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);
 }

Get HTML code

function Placehtmltoeditor (HTML)
{
  editablecontent.innerhtml = html;
}

4.oc and JS call each other

OC End instance a WebView load the HTML and a button to add a picture

  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];

Docking with HTML after adding pictures

 Rename the picture with a timestamp 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];//Global Array to save the added picture [Self.webview Stringbyevaluatingjavascriptfromstring:script];

When the editor is finished, take out the HTML code

  NSString *html = [Self.webview stringbyevaluatingjavascriptfromstring:@ document.getElementById (' content '). InnerHTML "];

Edit Rich text in a server

   NSString *place = [NSString stringwithformat:@ "Window.placehtmltoeditor ('%@ ')", self.inhtmlstring];
   [WebView Stringbyevaluatingjavascriptfromstring:place];

5. Docking with service end

At this point we take out the rich text as follows:

Penguin time to [stand outside the picture crosses ... (4)] <div> a red envelope in space? I </div>[the picture on the outside of the station. (5)] <div><br></div>

Where the ID part is a special part of my processing

The processing method is as follows

-(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;
}

Summarize

OK, so you can implement a new and edited Rich Text editor. The above is the entire content of this article, I hope that everyone's study or work can bring certain help, if there is doubt you can message exchange.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.