Search code examples
iphoneioshighlightnsattributedstringcore-text

Setting the background colour/highlight colour for a given string range using Core Text


I have some text laid out using Core Text in my iPhone app. I'm using NSAttributedString to set certain styles within the text for given ranges.

I can't seem to find an attribute for setting a background / highlight colour, though it would seem it is possible. I couldn't find an attribute name constant that sounded relevant and the documentation only lists:

kCTCharacterShapeAttributeName
kCTFontAttributeName
kCTKernAttributeName
kCTLigatureAttributeName
kCTForegroundColorAttributeName
kCTForegroundColorFromContextAttributeName
kCTParagraphStyleAttributeName
kCTStrokeWidthAttributeName
kCTStrokeColorAttributeName
kCTSuperscriptAttributeName
kCTUnderlineColorAttributeName
kCTUnderlineStyleAttributeName
kCTVerticalFormsAttributeName
kCTGlyphInfoAttributeName
kCTRunDelegateAttributeName

Craig Hockenberry, developer of Twitterrific has said publicly on Twitter that he uses Core Text to render the tweets, and Twitterrific has this background / highlight that I'm talking about when you touch a link.

alt text

Any help or pointers in the right direction would be fantastic, thanks.

Edit: Here's a link to the tweet Craig posted mentioning "Core text, attributed strings and a lot of hard work", and the follow up that mentioned using CTFrameSetter metrics to work out if touches intersect with links.


Solution

  • In the end, I had to use the Core Text metrics methods (getting the range, bounds, origins of lines etc) to calculate the bounding rectangle of the link. Once I had a rect for each line the link spanned, I drew the background into the context before redrawing the text above it.

    Seems like a hell of a lot of work, but it works.