Skip to content

tinyMCE html editor for Cocoa

One thing that’s been missing in MacOS X Cocoa is an easy way to add html editing features. A long time ago, in an operating system far away (NeXTSTEP, of course), it was simple enough to use Terminal Services to add almost anything you want, and I had a very useful set built for html markup for my own use. But with the advent of MacOS X, and loss of the ability to have tear off menus, this all went away, even though Terminal Services remained, to a certain extent. In the mean time, MacOS X gained WebKit, and the web got grown up javascript – in this case, tinyMCE.

So the problem is, how to integrate tinyMCE as an editor for Cocoa programs? The trick is simple: use a WebView (from WebKit), and figure out how to use javascript to manipulate the DOM from Objective-C. The rest is just standard web configuration for tinyMCE.

I put tinyMCE, a javascript file containing just the configuration for MCE (for separation of responsibilities), and an html file containing a named textarea, all in the Xcode resources.

Then create a NSView subclass, so that we can place it in Interface Builder. Use this as a wrapper for a WebView, which is initialised in initWithFrame:, and initialise it with loadHTMLString:baseURL: from resources. Then it needs a property to manipulate the textarea contents, which is slightly more obscure. WebKit supports stringByEvaluatingJavaScriptFromString: on WebViews, so we can use “tinyMCE.get(‘content’).getContent();” to read the html contents, and “tinyMCE.get(‘content’).setContent(‘%@’);” to replace it using a stringWithFormat: to insert the required string.

Demo attached, with a couple of alternative MCE configs. You can’t switch configs on the fly, but that shouldn’t be required. The html/javascript assumes that the textarea is called “content”, which, given the dedicated use within a WebView, seems reasonable. I have scrollbars enabled, so that behaviour on resizing accommodates tinyMCE’s fixed menu bars.

One quirk is that I use the NSView that I subclass purely to be able to position the program generated WebView using Interface Builder, and the actual NSView doesn’t draw itself. If you want to make any changes, then editor.html and mceconfig.js are the files used to create the WebView and embedded textarea, and MCEditor.h/MCEEditor.m are the class files. To use this in a project, drop in these four files, and add the tiny_mce folder into your project resources; the folder should be at the same level as the html and js files. It should be ok to replace the tiny_mce folder with an updated version.

Xcode can sometimes get confused with .js files, so you should drop mceconfig.js onto “Copy Bundle Resources” in the application target, and remove it from the “Compile Sources” build phase.

Source code

{ 1 } Trackback

  1. […] This post was mentioned on Twitter by . said: […]

Post a Comment

Your email is never published nor shared. Required fields are marked *