I have used CoreText for this purpose.
Calculating the tap offsets was a bit tricky, since I kept forgetting to flip the coordinate system, but I eventually got it, and here's a brief overview of how you can do it:
- Create your text as an
NSMutableAttributedString
(since you will have to modify it at some point).
- Scan it for the text you want to add a link to, insert two attributes: 1) A text colour that's for instance, blue; and 2) a custom link attribute (name it anything you like, make its value be the link you want to go to)
- Render the text in your
drawRect:
. You'll need to create a CTFramesetterRef
and a CTFrameRef
(the latter you'll want to keep around. Also note that creating a framesetter is an expensive process, do it only once (i.e., outside of drawRect:) if possible).
- In your touch handling code, as I mentioned earlier, you'll need to compensate for the different coordinate systems. From there, assuming you know where your text is using its coordinate system, you can figure out where on the text being rendered the tap was, which can then be intercepted in your touch handler, if the attribute over a particular
CTRunRef
contains your custom link attribute. If it does, simply get the attribute, and pass it to whatever -- typically this is where you'll want to use a delegate.
That's the crux of it.