获取多行标签中子字符串中的词框

Get frame of word in a substring in a multiline label

我想从有 2 行的标签文本中找到单词的位置和大小。

假设这是我的标签:

 ____________
|            |
|This is the |
|            |
|label       |
|____________|

我想找到单词 label 的框架,它类似于 {{0, 24}, {40, 24}} 但使用

- (CGRect)getFrameOfString:(NSString *)substring fromString:(NSString *)string inLabel:(UILabel *)label {

    NSRange range = [string rangeOfString:substring];
    NSString *prefix = [string substringToIndex:range.location];
    NSStringDrawingContext *stringDrawingContext = [[NSStringDrawingContext alloc] init];

    stringDrawingContext.minimumScaleFactor = 0.5;

    CGRect prefixFrame = [prefix boundingRectWithSize:label.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:[Util getAttributesforFont:label.font] context:stringDrawingContext];
    CGRect substringFrame = [substring boundingRectWithSize:label.frame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:[Util getAttributesforFont:label.font] context:stringDrawingContext];

    prefixFrame = CGRectIntegral(prefixFrame);
    substringFrame = CGRectIntegral(substringFrame);

    return CGRectMake(prefixFrame.size.width, prefixFrame.origin.y, substringFrame.size.width, substringFrame.size.height);
}

我得到 {{100, 0}, {40, 24}} 好像这个词的位置是这样的:

 ____________
|            |
|This is the |label
|            |
|            |
|____________|

我用这个解决了它:

+ (CGRect)getFrameOfString:(NSString *)substring inLabel:(UILabel *)label {

    NSString *string = label.text;
    CGRect labelFrame = label.frame;

    NSRange substringRange = [string rangeOfString:substring];
    NSString *prefixString = [string substringToIndex:substringRange.location];

    NSStringDrawingContext *stringDrawingContext = [[NSStringDrawingContext alloc] init];

    stringDrawingContext.minimumScaleFactor = label.minimumScaleFactor;

    CGRect prefixFrame = [prefixString boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, labelFrame.size.height) options:NSStringDrawingUsesLineFragmentOrigin attributes:[Util getAttributesforFont:label.font] context:stringDrawingContext];
    CGRect substringFrame = [substring boundingRectWithSize:labelFrame.size options:NSStringDrawingUsesLineFragmentOrigin attributes:[Util getAttributesforFont:label.font] context:stringDrawingContext];

    prefixFrame = CGRectIntegral(prefixFrame);
    substringFrame = CGRectIntegral(substringFrame);

    NSInteger labelWidth = labelFrame.size.width;

    BOOL isOnNextLine = prefixFrame.size.width >= labelWidth;

    CGFloat left = prefixFrame.size.width - (isOnNextLine ? labelWidth : 0); // the substrings on the other lines are offset by the label frame's width
    CGFloat top = isOnNextLine ? substringFrame.size.height : 0; // the substrings on the other lines have the top position equal to it's height
    CGFloat width = substringFrame.size.width;
    CGFloat height = substringFrame.size.height;

    return CGRectMake(left, top, width, height);
}

我认为它现在只适用于两行标签。