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

≯℡__Kan透↙ 提交于 2019-12-17 23:27:48

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/7514648/how-to-get-coordinates-cgrect-for-the-selected-text-in-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!