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):
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
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.
精彩评论