Wednesday, March 28, 2012

Syntax Highlighting in iOS

The Problem

One of the controls included with the UIKit framework of iOS is the UITextView. It handles all text editing tasks including line wrapping, copy and paste operations, and undo. The only thing it lacks is text styling. But starting from iOS 4.0 Apple added the CoreText framework. This framework gives you the ability to draw text with different styles and colors. The problem is integrating the text styling features of CoreText with the text editing features of UIKit.

The only successful reports of doing syntax highlighting involve either rewriting all editing features of an UITextView like in OmniUI, or using a UIWebView with JavaScript to handle the highlighting as described here and here.

I found a way of reusing a UITextView with custom drawing using CoreText.