ios - 为 UITextView 中的文本获取 CGRect 以使用 CALayer 突出显示

标签 ios uitextview calayer textkit nstextcontainer

我试图在 UITextView 中绘制一个透明的 CALayer,以便在搜索中突出显示匹配的文本。

我已经想出了正确的方法,但仍然没有找到正确的坐标。我需要找到文本容器的来源。现在,我得到了 textView 的原点,并以此偏移图层的原点:

NSRange match = [[[self textView]text]rangeOfString:@"predict the future"];
NSRange glyphRange = [manager glyphRangeForCharacterRange:match actualCharacterRange:NULL];

CGRect textRect = [manager boundingRectForGlyphRange:glyphRange inTextContainer:[[self textView]textContainer]];

CGPoint textViewOrigin = self.textView.frame.origin;
textRect.origin.x += (textViewOrigin.x / 2);
textRect.origin.y += (textViewOrigin.y / 2);


CALayer* roundRect = [CALayer layer];
[roundRect setFrame:textRect];
[roundRect setBounds:textRect];

[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];

如果我移动文本字段,或者如果我不将偏移量除以 2,我会得到以下结果: The layer frame is off

我想知道我是否走在正确的轨道上,如果是这样,我还想知道如何找到 NSTextContainer 对象的来源。

最佳答案

要正确定位图层,您只需将 self.textView.textContainerInset.top 添加到 textRect.origin.y,而不是 TextView 的原点。

但正如我在评论中所说,如果你的比赛跨越两行,它就不会很好地工作。您可能想要设置匹配范围的背景颜色以突出显示它(使用 attributedText 属性),但是您无法添加圆角或阴影。

关于ios - 为 UITextView 中的文本获取 CGRect 以使用 CALayer 突出显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20599431/

相关文章:

ios - 在 ABAddressBookSave 上获取 EXC_BAD_ACCESS

ios - Cocos2d iPhone v3.0 - 向上滑动执行 Action

ios - FBSDKLoginKit 在 pod 安装后中断

iOS,键盘预测栏可见性

ios - 更改字体大小以适合 UITextView

iOS 6 '-[UITextView setTextContainerInset:]: unrecognized selector sent to instance 0x1d68e600'

php - iOS HTML POST 请求

multithreading - NSOpenGLLayer 和多线程

swift - 将 UIPercentDrivenInteractiveTransition 与 CABasicAnimation 一起使用会出现奇怪的故障

ios - 如何使 CALayer 可点击?