我想从标签的文本中找到有两行的单词的位置和大小。
我们假设这是我的标签:
____________
| |
|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
| |
| |
|____________|
答案 0 :(得分:1)
我用这个解决了它:
+ (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);
}
我认为它现在只适用于有两行的标签。