开发者

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

开发者 https://www.devze.com 2023-04-06 12:39 出处:网络
I have simple UIWebView with loaded html. I want to show the PopoverView pointed to the selected text.

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 开发者_StackOverflowthe selection may be found, but I want exactly know where is the selected text. Is it generally possible?


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

精彩评论

暂无评论...
验证码 换一张
取 消