Search code examples
cocoa-touchioscore-text

NSAttributedString and Links on iOS


I am trying to add a hyperlink to certain parts of my text which is being handled and drawn using CoreText.

According to Apple's docs on CoreText I should be using addAttribute:NSLinkAttributeName however on iOS (4.3) it says it doesn't know NSLinkAttributeName. In my document searches it looks like NSLinkAttributeName only still exists on the Mac.

Is it available on iOS and I am just missing something? If it's not available how can I create a hyperlink on part of a text using NSMutableAttributedString and CoreText?

Thanks


Solution

  • Jeremy has published JTextView, a Core Text-based UITextView analogue that supports attributed text, including links.

    In a nutshell, JTextView:

    • Creates its own attribute for links by using a custom name for the attribute name and the attribute value contains a representation of the corresponding URL
    • In -drawRect:, it uses a data detector for links. If a link has been found, it sets its custom attribute for the corresponding range
    • In its tap gesture recogniser method, it gets the line frame that contains the tap point. For each glyph run in that line, it gets its attributes and checks whether they contain the custom attribute for links. If so, it opens the URL.