How to get coordinates (CGRect) for the selected text in UIWebView?

前端 未结 1 1284
名媛妹妹
名媛妹妹 2020-12-14 19:40

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

相关标签:
1条回答
  • 2020-12-14 20:30

    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 + "}}";
    }
    

    and in a category on UIWebView, you could use it like such:

    - (CGRect)rectForSelectedText{
        CGRect selectedTextFrame = CGRectFromString([self stringByEvaluatingJavaScriptFromString:@"getRectForSelectedText()"]);
        return selectedTextFrame;
    }
    
    0 讨论(0)
提交回复
热议问题