如何在UIWebView中获取所选文本的坐标(CGRect)? [英] How to get coordinates (CGRect) for the selected text in UIWebView?

查看:244
本文介绍了如何在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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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