7

My objective is simple: From a UILabel get the rect of a substring in the text of the label. From extensive searching there doesn't appear to be anything built in to handle this. Other people have asked similar questions, but none have been answered fully here on Stackoverflow.

// Something like this perhaps (added as a category)
CGRect rect = [myLabel rectForRange:NSMakeRange(3, 5)];

An example of what it could be used for (just to clarify what I'm searching for):

example of rect

Erik Rothoff
  • 4,826
  • 9
  • 41
  • 59

2 Answers2

7

This was mostly needed for one character rects, so I went crazy and wrote some code that could accurately calculate the rect for the most basic UILabel. Standard UILineBreakMode and text alignment.

I was hoping that if I release it to the public people code contribute to it and improve it, especially since I don't know so much about text rendering!

The code:

https://gist.github.com/1278483

Erik Rothoff
  • 4,826
  • 9
  • 41
  • 59
  • Hi Erik. It will be really great if you can help me [here](http://stackoverflow.com/questions/8860520/find-coordinates-of-a-substring-in-uilabel). – Nitish Jan 14 '12 at 06:40
2

You're right: this isn't a built-in part of UILabel.

If you really need this, subclass UILabel, use CoreText to implement -drawRect:, and you'll be able to compute the rect for a range via CTLineGetOffsetForStringIndex(), CTFrameGetLineOrigins(), and CTLineGetTypographicBounds(). If the text in the range gets laid out so as to cross a line break, this will get complicated; you'll likely want multiple rects.

lemnar
  • 4,063
  • 1
  • 32
  • 44