How to use the fastest speed and the most simple markdown editor

How to use the fastest speed and the most simple markdown editor


I believe a lot of buddy I read ahead of the “iOS UIWebView and WKWebView, JavaScript and OC Cookie management interaction, I had enough” series of it, the author introduced a lot about the interaction of Native and JS use. Today, I use the fastest speed and the most simple Markdown editor.

In fact, there are many ways to realize the native iOS Markdown editor, Github on some of the more powerful database, the spirit does not reinvent the principle of pure markdown text to HTML string, this part does not realize his other part with a combination of JavaScriptCore and JS and OC (Swift is the same), to achieve a simple the Markdown editor.

This article is not to teach you how to develop the Markdown editor, but opens a new way for the majority of iOS developers, we can not only use the open source iOS library with JavaScriptCore, even without WebView, we can also use the JavaScript open source library.

Below for small partners introduced specific implementation details, the source code has been uploaded Github, I hope the small partners like to a Star.

Catalogue of this article

  • Preface
  • Analysis
  • programme
  • Build UI logic initialization, add toolbar preview save
  • Beautify style
  • summary


How do you implement a markdown editor on iOS? Let’s analyze it.

  • First of all, since it’s an editor, you should use the UITextView control.
  • Second, the user is the text entered on the UITextView, which should have a preview function as an editor, and click the preview to see the HTML page.
  • Again, click preview to implement markdown plain text to HTML string. How do you do that?
  • Finally, consider adding some users used button to UITextView inputAccessoryView, such as “#, link, IMG etc., is convenient for users to operate.


The above is the author in a markdown editor’s ideas, in fact this is very important, in the face of buddies and handle problems, should also be the first overall thinking, analysis, and the implementation scheme, finally to implement and develop a good habit.

The author’s plan is as follows:

  • Page structure: a UIViewController with a UITextView on top, a preview button and a save button on top of NavigationBar. Click on the preview to see the edited preview page. Click Save to save the current article to the sandbox directory (the actual business requirements may be sent).
  • UITextView markdown pure text to HTML string, through the mature JS to achieve, as for interaction, using JavaScriptCore (do not repeat the wheel, do not write their own regular processing).
  • The preview page loads the HTML string directly with WebView.


Build UI

This So easy, minute minutes ~ as follows

How to use the fastest speed and the most simple markdown editor
UI build

The diagram above is clear enough

The edit page holds a JSContext object, holding a inputBar, a TextView (text), and a UITextField (Title).

The preview page is a UIWebView (or WKWebView).

Logical processing


The initialization method is first implemented in EditViewController.

- (void) initialize {self.textView.textContainerInset = UIEdgeInsetsMake (10, 5, 10, 5); / / [self.jsContext (JSContext *context setExceptionHandler:^ error correction, JSValue *exception) {NSLog ("% @ @", exception.toString);}]; //markdown -> HTML JS static NSString *js static; dispatch_once_t onceToken; dispatch_once (& onceToken ^{, JS = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@ "showdown" ofType:@ "JS"] encoding:NSUTF8StringEncoding error:nil];}); / / evaluateScript:js] / / [self.jsContext JS loading; markdown -> HTML, function injection; when used by convert ('xxx'); NSString *jsFu call Nction = "@ function / convert (MD) {return (New / showdown.Converter) (.MakeHtml) (MD); [self.jsContext / evaluateScript:jsFunction];}}";

In the code above, we inject showdown.js files into jsContext in advance, and then use the (new, showdown.Converter ()).MakeHtml (MD) method to convert the markdown string into a HTML string. Well, we’ve also injected a method convert function for our own calls.

Add Tool Bar

There are some characters, such as “*”, “-“, etc., are very common, here we add a toolbar, easy for users to operate quickly. We add the following method in the initialization method initialize.

Self.textView.inputAccessoryView = self.inputBar;

When the user clicks the button on the inputBar, the event is triggered:

Click on the above toolBar / * * item @param item * / item - (IBAction) inputBarItemClicked: (UIBarButtonItem * item) {NSString *title = item.title; / / NSString text *insertText insertion; / / insert text, move the cursor to the specified location NSRange selectedRange = self.textView.selectedRange; if ([title isEqualToString:@ "link"] = insertText) {@ "([]); selectedRange.location + = 1; / / mobile else if} to the back ([title isEqualToString:@" img "] = insertText) {@! ([]); selectedRange.location + = 4; / / move to else (behind} {insertText = title; selectedRange.location = title.length; / / move to insert text at last} / / insert text [sel F.textView insertText:insertText]; / / self.textView.selectedRange cursor = selectedRange;}

Effect is as follows

How to use the fastest speed and the most simple markdown editor
toolbar input


At this point, the user can happily edit the content and click preview when the user edits it. Preview method implementation:

@param sender item * / / * * Preview - (IBAction) preview: (ID sender) {/ / Title cannot be empty (if! Self.titleTextField.text.length) {[self showMessage:@ "please fill in the title"]; return;} / / [self performSegueWithIdentifier:kShowPreviewSegueId preview page Jump to sender:self]; #pragma mark - Setters and Getters} - {htmlString (NSString *) //markdown -> HTML JSValue *jsFunctionValue = self.jsContext[@ "convert"]; JSValue *htmlValue = [jsFunctionValue callWithArguments:@[self.textView.text]]; return [NSString stringWithFormat:@ / < / < head> html> title>%@< < /title> < / / < B; /head> Ody>%@/ / < /body> /html> / / < "self.titleTextField.text, htmlValue.toString], #pragma mark;} - Navigation - (void) prepareForSegue: (UIStoryboardSegue *) segue sender: (ID sender) {/ / jump to the preview page if ([segue.identifier isEqualToString:kShowPreviewSegueId]) {PreviewViewController *vc = segue.destinationViewController; vc.htmlString = [self htmlString]; vc.title = self.titleTextField.text;}}

Click on the preview, jump to the PreviewViewController page, and pass the htmlString. How do I get htmlString here? Previously, we injected the method named convert in advance in the initialize method, and now we call it

JSValue *jsFunctionValue = self.jsContext[@ "convert"]; JSValue *htmlValue = [jsFunctionValue callWithArguments:@[self.textView.text]];

The string that we can get the markdown text into HTML, then we give this string to improve, add HTML tag, head tag and title page, and then transmitted to the preview page, direct display on OK.

The effect is shown below

How to use the fastest speed and the most simple markdown editor
click Preview


In fact, save, here is simply a realization, save to sand box. The actual business requirement is likely to be a send button, upload to the server, or share it with other App. Here briefly introduced to save to the sandbox. Following code

Save to the sandbox directory @param sender / * * item * / - (IBAction) save: (ID sender) {/ / Title cannot be empty (if! Self.titleTextField.text.length) {[self showMessage:@ "please fill in the title"]; return;} NSData *data = [self.textView.text dataUsingEncoding:NSUTF8StringEncoding]; NSString *documentPath = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES).FirstObject; NSString *filePath = [documentPath stringByAppendingPathComponent:[NSString, self.titleTextField.text]] [data writeToFile:filePath atomically:YES]; / / write the file; NSLog (@ MD saved successfully, filePath address% @ "); [self showMessage:@;}" save "

When you save, just save the source code to the local, just name the file titled.Md.

When I click save, save to local and output at the same time

DAMarkdownEditor[9717:192504] MD /Users/DarkAngel/Library/Developer/CoreSimulator/Devices/CF831783-E4A6-4EC2-AB99-E04304331C3A/data/Containers/Data/Application/A7837233-9EC3-4E4C-94CB-252329746176/Documents/A test address saved successfully

We’ll use Safari, Cmd+Shift+G, and open the address above to see

The How to use the fastest speed and the most simple markdown editor
MD file is saved

Open this file, you can view, the source code is what we entered.

As a matter of fact, here we have completed a simple Markdown editor. But the buddies might say, preview of the HTML code block in the middle of the ugly, not bright. How can that be solved?

Beautify style

If you have a little bit of front-end knowledge, you’ll immediately think of a less attractive CSS style. We can make the page look better by adding CSS to the html.

Next, we add CSS to HTML in the – (NSString *) htmlString method, where I add a CSS file directly to the head tag

- (NSString *) htmlString //markdown HTML JSValue *jsFunctionValue {-> self.jsContext[@ = "convert"]; JSValue *htmlValue = [jsFunctionValue callWithArguments:@[self.textView.text]]; static NSString *css / / css style loading; static dispatch_once_t onceToken; dispatch_once (& onceToken, CSS [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@ ^{= "markdown" ofType:@ "CSS" encoding:NSUTF8StringEncoding error:nil] ";}) return; [NSString / < html> stringWithFormat:@ / < head> title>%@< < /title> style>%@< < /style> /head> / / < < body> / %@/ < /body> /html> / / < self.titleTextField.text, CSS, htmlValue.toString] ";}

OK, let’s click on the preview again

After How to use the fastest speed and the most simple markdown editor
adds CSS, click Preview

This looks much better, if the small partners want to customize the style, only need to modify the CSS file on the OK, of course, there are many good Github style Oh ~ can look to see, you can also modify the css.

So far, our Markdown editor has been completed, EditViewController has 181 lines, PreviewViewController has 38 lines, plus a simple Storyboard, our editor is very refreshing. After the follow-up, you can optimize the page under the UI, InputBar, add a number of shortcut buttons, optimize UE, we can upload AppStore ~!


We use a little code above, little time to complete a simple Markdown editor, once again proved that JavaScriptCore is powerful, it also proved that the front end is so hot today, Native development is still the key.

Of the top ten open source projects in Github, six are based on the JavaScript language. There may be some small partners as a Native end developer, will be very square, many small partners began to learn the front end, learning js. Of course, learning something new is understandable. But I believe that the passive learning is not in the minority.

So, can we use it to build a better App with Native? The answer is: definitely.