Finding the location of specific characters in UILabel on iPhone

I have a UILabel with some text like "Hello World abcdefg". A label can contain several lines, different font sizes, etc.

Question: How to find the coordinates of all the letters "d" in this UILabel.

The logical first step is to find the position of these characters in the string (UILabel.text), but then how can I translate this into coordinates when it is actually displayed on the screen

The idea is to find these coordinates and draw something custom on top of this symbol (basically to cover it with a custom image)

+5
source share
2 answers

The basic tools for measuring text on the iPhone are in UIStringDrawing.h , but none of them do what you need. Basically you will have to iterate over the substrings one character at a time, measuring each. When the line wraps (the result is higher), separate after the last character that did not wrap or add the line height to your y coordinate.

 - (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode; 
+3
source

Methods have changed since iOS 7.0. try it

 - (CGFloat)charactersOffsetBeforeDayPartOfLabel { NSRange range = [[self stringFromDate:self.currentDate] rangeOfString:[NSString stringWithFormat:@"%i",[self dayFromDate:self.currentDate]]]; NSString *chars = [[self stringFromDate:self.currentDate] substringToIndex:range.location]; NSMutableArray *arrayOfChars = [[NSMutableArray alloc]init]; [chars enumerateSubstringsInRange:NSMakeRange(0, [chars length]) options:(NSStringEnumerationByComposedCharacterSequences) usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { [arrayOfChars addObject:substring]; }]; CGFloat charsOffsetTotal = 0; for (NSString *i in arrayOfChars){ NSDictionary *attributes = @{NSFontAttributeName: [UIFont fontWithName:@"Helvetica Neue" size:16.0f]}; charsOffsetTotal += [i sizeWithAttributes:attributes].width; } return charsOffsetTotal; } 
+1
source

All Articles