Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel get CGRect for substring of text

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

like image 495
Erik Rothoff Avatar asked Jul 24 '11 19:07

Erik Rothoff


2 Answers

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

like image 62
Erik Rothoff Avatar answered Sep 21 '22 11:09

Erik Rothoff


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.

like image 30
lemnar Avatar answered Sep 19 '22 11:09

lemnar