UILabel gets CGRect for text substring

My goal is simple: from UILabel we get the rectangle of the substring in the label text. From the extensive search, nothing seems to have been created to handle this. Other people asked similar questions, but no one got the full answer here on Stackoverflow.

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

An example of what it can be used for (just to find out what I'm looking for):

example of rect

+7
source share
2 answers

This was mostly necessary for a single rects character, so I went crazy and wrote code that could accurately calculate the rectangle for the most basic UILabel. Standard UILineBreakMode and text alignment.

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

The code:

https://gist.github.com/1278483

+7
source

You are right: this is not a built-in part of UILabel .

If you really need it, a subclass of UILabel , use CoreText to implement -drawRect: and you can calculate the rectangle for the range via CTLineGetOffsetForStringIndex() , CTFrameGetLineOrigins() and CTLineGetTypographicBounds() . If the text in the range is laid out in such a way as to cross the line break, this will become more complicated; you will probably need a few fixes.

+2
source

All Articles