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?
Asked
Active
Viewed 5,520 times
1 Answers
15
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;
}

Nishant Tyagi
- 9,893
- 3
- 40
- 61

hwaxxer
- 3,363
- 1
- 22
- 39
-
I have tried but it returns {(0,0),(0,0)} could you help me please – dineshprasanna Mar 23 '13 at 04:41
-
1If we set the scalesPageToFit property of UIWebView then it does not work as expected. Any other solution for same.? – Girish Oct 18 '13 at 12:23
-
how to get start and end range of webview selected text – Rakesh kumar Mar 03 '16 at 10:12