这是一个延续获取 UITextView 中文本的 CGRect,以便使用 CALayer 突出显示。我无法为每个行片段中的范围获取正确的矩形。
NSString* searchString = @"Returns the range of characters that generated";
NSRange match = [[[self textView]text]rangeOfString:searchString];
NSRange matchingGlyphRange = [manager glyphRangeForCharacterRange:match actualCharacterRange:NULL];
[manager enumerateLineFragmentsForGlyphRange:matchingGlyphRange usingBlock:
^(CGRect lineRect, CGRect usedRect, NSTextContainer *textContainer, NSRange lineRange, BOOL *stop) {
NSRange currentRange = NSIntersectionRange(lineRange, matchingGlyphRange);
[manager enumerateEnclosingRectsForGlyphRange:currentRange withinSelectedGlyphRange:NSMakeRange(NSNotFound, 0) inTextContainer:textContainer usingBlock:
^(CGRect rect, BOOL* stop) {
if (usedRect.origin.y == rect.origin.y && NSLocationInRange(currentRange.location, lineRange)) {
CGRect theRect = [manager boundingRectForGlyphRange:currentRange inTextContainer:textContainer];
CALayer* roundRect = [CALayer layer];
[roundRect setFrame:theRect];
[roundRect setBounds:theRect];
[roundRect setCornerRadius:5.0f];
[roundRect setBackgroundColor:[[UIColor blueColor]CGColor]];
[roundRect setOpacity:0.2f];
[roundRect setBorderColor:[[UIColor blackColor]CGColor]];
[roundRect setBorderWidth:3.0f];
[roundRect setShadowColor:[[UIColor blackColor]CGColor]];
[roundRect setShadowOffset:CGSizeMake(20.0f, 20.0f)];
[roundRect setShadowOpacity:1.0f];
[roundRect setShadowRadius:10.0f];
[[[self textView]layer]addSublayer:roundRect];
*stop = YES;
}
}];
}];
这是我目前的尝试。我基本上使用 enumerateLineFragmentsForGlyphRange:usingBlock: 循环遍历每一行。然后我使用 enumerateEnendingRectsForGlyphRange:withinSelectedGlyphRange:usingBlock: 确保当前行上的文本范围与该行的范围匹配并具有相同的 Y 坐标。有时这有效,有时则无效。
看起来,如果搜索文本靠近回车符,它会将突出显示的内容拉远。 (y 坐标)。
在此屏幕截图中,“返回生成的字符范围”应该突出显示。
看来如果文本不在回车符或空格附近,则可以正常工作:
我错过了什么吗?
UPDATE:
我已经缩小了问题范围,我相信 enumerateLineFragmentsForGlyphRange: usingBlock: 正在跳过有返回的行。