如何在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;
}