2

A UILabel's text is drawn in a CGRect(x,y,size,width). The label can have multiple lines of text.

Is it possible to write a function to return a CGPoint within this rectangle that designates the position of the last character?

I ask because I am trying to wrap the text of a UILabel in an arbitrary prefix and suffix. The prefix/suffix need to be separate labels so I can set their font, color, etc. It's easy to find the start of the text, but finding the end of the text is tricky, to me at least.

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
Andrew Johnson
  • 13,108
  • 13
  • 75
  • 116
  • 1
    Possible duplicate of [How do I locate the CGRect for a substring of text in a UILabel?](https://stackoverflow.com/questions/19417776/how-do-i-locate-the-cgrect-for-a-substring-of-text-in-a-uilabel) – Cœur Mar 23 '18 at 10:47

3 Answers3

1

Perhaps a UIWebView will do the trick. Populate it with [webview LoadHTMLString:@"<b>prefix/b>text<b>suffix</b>" baseURL:nil]. This is a bit of a sledgehammer solution, but you obviously get lots of other goodies thrown into the bargain.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
0

As sbooth mentioned, you can use the following to get a text rect:

UILabel *label = [UILabel new]; // Or whatever the label happens to be...
CGSize constraintSize = CGSizeMake(label.frame.size.with-10, MAXFLOAT); // 10 is the total size of the margins. 
// Replace the 10 with 40 for UITableView usage because of the other subviews
CGSize labelSize = [label.text sizeWithFont:label.font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

To get a point for the last character, just isolate the last line and get its rect.

X: Get rect of last line and subtract 0.5*(width of last character)
Y: 0.5*labelSize.height

Nate Symer
  • 2,185
  • 1
  • 20
  • 27
0

The main way to measure text on the iPhone is using NSString's sizeWithFont:forWidth:lineBreakMode. It is possible to build on this to do what you want, but it would be a bit of work. First, measure the prefix using your specified text traits and remember the dimensions. Then, calculate word breaks and incrementally add the measured widths for each word, line wrapping as necessary. Finally, measure your suffix and draw everything in the rectangles you've calculated.

sbooth
  • 16,646
  • 2
  • 55
  • 81