问题描述
我有简单的 UIWebView 和加载的 html.我想显示指向所选文本的 PopoverView.我可以获取 UIMenuController 的 menuFrame 并使用它的 rect,但结果在屏幕的角落并不像我需要的那样准确.我可以计算屏幕大小并获取 menuFrame rect,然后我可以假设可以在哪里找到选择,但我想确切地知道所选文本在哪里.一般可以吗?
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?
推荐答案
您可以在所选文本的范围对象上使用 javascript 函数 getBoundingClientRect().我就是这样做的:
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 + "}}";
}
在 UIWebView 的一个类别中,你可以这样使用它:
and in a category on UIWebView, you could use it like such:
- (CGRect)rectForSelectedText{
CGRect selectedTextFrame = CGRectFromString([self stringByEvaluatingJavaScriptFromString:@"getRectForSelectedText()"]);
return selectedTextFrame;
}
这篇关于如何获取 UIWebView 中选定文本的坐标(CGRect)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!