finding location of specific characters in UILabel

2019-01-19 05:36发布

I have a UILabel with some text, say "Hello World abcdefg" The label can have multiple lines, different font sizes etc.

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

Logical first step is find the position of those characters in the string (UILabel.text), but then how do I translate that into coordinates when it's actually drawn on screen

The idea is to find those coordinates and draw something custom on top of that character (basically to cover it with a custom image)

2条回答
SAY GOODBYE
2楼-- · 2019-01-19 06:12

Methods have changed since iOS 7.0 came out. Try this

- (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;
}
查看更多
Evening l夕情丶
3楼-- · 2019-01-19 06:30

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

- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode;
查看更多
登录 后发表回答