Find the CGPoint of a specific character in NSString/UILabel within the superview

671 views Asked by At

Let's say I have a UILabel and the text is "Hello World". If I want to find the CGPoint value of the 'W' so that I can create a duplicate label with just a 'W' right on top of the old 'W', how would I do that?

1

There are 1 answers

0
rmaddy On BEST ANSWER

At a high level you can calculate the size of the text up to the letter.

UILabel *label = ... // label with "Hello World"
NSDictionary *attrs = @{ NSFontAttributeName : label.font };
CGSize size = [@"Hello " sizeWithAttributes:attrs];

CGPoint newOrigin = label.frame.origin;
newOrigin.x += size.width;

At this point newOrigin should represent the original needs for the new label containing the "W".

Create the new label with the same font and height as the original label. Use newOrigin as the new label's origin.

The code makes several assumptions:

  1. label is set for left alignment
  2. label is properly sized for the font (not too tall, not too short, not too narrow - resulting in a smaller font)

With a bit more work, those assumptions can be removed.