在UITextView中为文本获取CGRect以便使用CALayer突出显示 [英] Getting CGRect for text in a UITextView for the purpose of highlighting with a CALayer

查看:109
本文介绍了在UITextView中为文本获取CGRect以便使用CALayer突出显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to draw a transparent CALayer in a UITextView in order to highlight matched text in a search.

我已经找到了执行此操作的正确方法,但是仍然没有找到正确的坐标.我需要找到文本容器的来源.现在,我得到了textView的原点,并通过该点偏移了图层的原点:

I've figured out the correct way to do this, but still haven't found the correct coordinates. I need to find the origin of the text container. Right now, I get the textView's origin, and offset the layer's origin by that:

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,则会得到以下结果:

I get the following result if I move the text field, or if I don't divide the offsets by 2:

我想知道我是否处在正确的轨道上,如果想要的话,还想知道如何找到NSTextContainer对象的原点.

I'd like to know if i'm on the right track and also how to find the NSTextContainer object's origin if so.

推荐答案

要正确放置图层,只需将self.textView.textContainerInset.top添加到textRect.origin.y,而不是文本视图的原点.

To position the layer correctly, you only have to add self.textView.textContainerInset.top to textRect.origin.y, not the text view's origin.

但是正如我在评论中说的那样,如果您的比赛跨越两行,效果将不佳.您可能想要设置匹配范围的背景颜色以突出显示(使用attributedText属性),但是这样就不能添加圆角或阴影.

But as I said in the comment, it won't work nicely if your match is across two lines. You may want to set the background colour of the matched range to highlight it, (using the attributedText property), but then you can't add the rounded corners or shadow.

这篇关于在UITextView中为文本获取CGRect以便使用CALayer突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆