How to get coordinates (CGRect) for the selected text in UIWebView?(如何获取 UIWebView 中选定文本的坐标(CGRect)?)
问题描述
我有简单的 UIWebView 和加载的 html.我想显示指向所选文本的 PopoverView.我可以获取 UIMenuController 的 menuFrame 并使用它的 rect,但结果在屏幕的角落并不像我需要的那样准确.我可以计算屏幕大小并获取 menuFrame rect,然后我可以假设可以在哪里找到选择,但我想确切地知道所选文本在哪里.一般可以吗?
I have simple UIWebView with loaded html. I want to show the PopoverView pointed to the selected text. I can get the menuFrame of the UIMenuController and use its rect, but the result isn't as accurate at the corners of the screen as I need. I can calculate the screen size and get menuFrame rect and then I can suppose where the selection may be found, but I want exactly know where is the selected text. Is it generally possible?
推荐答案
您可以在所选文本的范围对象上使用 javascript 函数 getBoundingClientRect().我就是这样做的:
You can use the javascript function getBoundingClientRect() on the range object of the selected text. This is how I do it:
function getRectForSelectedText() {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var rect = range.getBoundingClientRect();
return "{{" + rect.left + "," + rect.top + "}, {" + rect.width + "," + rect.height + "}}";
}
在 UIWebView 的一个类别中,你可以这样使用它:
and in a category on UIWebView, you could use it like such:
- (CGRect)rectForSelectedText{
CGRect selectedTextFrame = CGRectFromString([self stringByEvaluatingJavaScriptFromString:@"getRectForSelectedText()"]);
return selectedTextFrame;
}
这篇关于如何获取 UIWebView 中选定文本的坐标(CGRect)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何获取 UIWebView 中选定文本的坐标(CGRect)?


基础教程推荐
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01