获取CGRect以获取UITextView中的文本,以便使用CALayer进行突出显示

 一腕儿本人 发布于 2023-02-10 12:17

我试图在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,则得到以下结果: 图层框架已关闭

我想知道我是否在正确的轨道上,以及如何找到NSTextContainer对象的起源.

1 个回答
  • 要正确定位层,你只需要添加self.textView.textContainerInset.toptextRect.origin.y,而不是文本视图的原点.

    但正如我在评论中所说,如果你的比赛跨越两条线,它将无法奏效.您可能需要设置匹配范围的背景颜色以突出显示它(使用attributedText属性),但是您无法添加圆角或阴影.

    2023-02-10 12:20 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有