Attributed Markdown

Display Markdown formatted text with standard UIKit components on iOS 6.

turns this...

into this.

The idea behind Markdown is to let one write without thinking too much about syntax, while at the same time making it easy to create semantically correct, well-structured documents. It's lightweight and well-suited for including in formats like JSON.

I recently wanted a way to take Markdown formatted text and display it nicely-formatted in standard iOS UIKit components, without using UIWebView. AttributedMarkdown solves this by converting to NSAttributedString, an Objective-C object useful for rendering text in native apps.

How does it work?

Peg-Markdown tokenizes the raw markdown into distinct elements like headers, paragraphs, links, etc, and provides a set of functions for printing each element uniquely. AttributedMarkdown modifies the main recursive print functions to assign attribute dictionaries to character ranges and return an NSAttributedString object. It implements basic 'cascading' styles by merging attributes during the element recursion (specifically it uses CoreText functions to bitmask inherited font traits together).

Basic link support is outlined in the sample project. At this time iOS does not support NSLinkAttributeName, so we use a generic key. The View Controller is responsible for handling taps and seeing if the user has touched a range of characters which were assigned the link attribute.

As of iOS 6, many native UIKit components like UILabel and UITextField now have attributedText properties, meaning they can render NSAttributedStrings just by assigning them.

Who made this?

It was written by myself and my friend Jim Radford, on top of a Markdown to NSString library parser called Peg-Markdown.

Fork AttributedMarkdown on GitHub.

< return home