如何在UIWebView中获取所选文本的坐标(CGRect)?

adn*_*ako 15 textselection uiwebview coordinates ios cgrect

我有简单的UIWebView和加载的HTML.我想显示指向所选文本的PopoverView.我可以获取UIMenuController的menuFrame并使用它的rect,但结果并不像我需要的那样在屏幕的角落准确.我可以计算屏幕大小并获取menuFrame rect然后我可以假设可以找到选择的位置,但我想知道所选文本的位置.一般可能吗?

hwa*_*xer 15

您可以在所选文本的范围对象上使用javascript函数getBoundingClientRect().我是这样做的:

function getRectForSelectedText() {
    var selection = window.getSelection(); 
    var range = selection.getRangeAt(0); 
    var rect = range.getBoundingClientRect(); 
    return "{{" + rect.left + "," + rect.top + "}, {" + rect.width + "," + rect.height + "}}";
}
Run Code Online (Sandbox Code Playgroud)

在UIWebView上的类别中,您可以像这样使用它:

- (CGRect)rectForSelectedText{
    CGRect selectedTextFrame = CGRectFromString([self stringByEvaluatingJavaScriptFromString:@"getRectForSelectedText()"]);
    return selectedTextFrame;
}
Run Code Online (Sandbox Code Playgroud)