我有一个简单的 UIWebView
,其中加载了html文件。 我希望将 PopOverController
显示在所选文本上,如下图所示:
.
我想要从 UIWebView
中获取所选文本的 coordinates
。如果我将 UIWebView
的 scalesPageToFit
属性设置为 NO
,那么此链接可以正常工作。如果我将 UIWebView
的 scalesPageToFit
属性设置为 YES
,则会失败。
请任何人帮助我解决这个问题。
我有一个简单的 UIWebView
,其中加载了html文件。 我希望将 PopOverController
显示在所选文本上,如下图所示:
.
我想要从 UIWebView
中获取所选文本的 coordinates
。如果我将 UIWebView
的 scalesPageToFit
属性设置为 NO
,那么此链接可以正常工作。如果我将 UIWebView
的 scalesPageToFit
属性设置为 YES
,则会失败。
请任何人帮助我解决这个问题。
首先,像这样移除本地的长按手势识别器:
for(UIGestureRecognizer *gesRecog in yourWebView.gestureRecognizers)
{
if([gesRecog isKindOfClass:[UILongPressGestureRecognizer class]])
{
[startTF removeGestureRecognizer:gesRecog];
}
}
UILongPressGestureRecognizer *myOwnLongPressRecog = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleWebViewLongpress:)];
// set numberOfTapsRequired and numberOfTouchesRequired as per your requirement:
[yourWebView addGestureRecognizer:myOwnLongPressRecog];
// 处理长按事件的方法:
- (void) handleWebViewLongpress: (UIGestureRecognizer *) recog
{
int zoomedWidth = [[yourWebView stringByEvaluatingJavaScriptFromString:@"window.innerWidth"] intValue];
CGFloat scale = yourWebView.frame.size.width / zoomedWidth; // get the scaled value of your web view
CGPoint zoomedCords = [gesture locationInView:self.webView];
zoomedCords.x /= scale; // Normal math. Divide by the scale to get the real thing.
zoomedCords.y /= scale;
NSLog(@"%@", zoomedCords);
}
<script>
标记中。否则,您需要按照this post中所述进行注入。function rectsForSelection() {
var i = 0, j = 0;
var allSelections = window.getSelection();
var result = []; // An empty array right now
// Generally, there is only one selection, but the spec allows multiple
for (i=0; i < allSelections.rangeCount; i++) {
var aRange = allSelections.getRangeAt(i);
var rects = aRange.getClientRects();
for (j=0; j<rects.length; j++) {
result.push(rects[j]);
}
}
return JSON.stringify(result);
}
NSString *rectsString = [webView stringByEvaluatingJavaScriptFromString:@"rectsForSelection();"];
NSData *rectsData = [rectsString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *rects = [NSJSONSerialization JSONObjectWithData:rectsData
options:0
error:NULL]; //Do Your Own Error Checking
我补充一点,这将获取在您的webView.scrollView
内有效的坐标,而不是您的webView
。
你试过了吗?
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(getCoordinates:)];
// [longPress setMinimumPressDuration:1];
[yourWebView addGestureRecognizer:longPress];
- (void)getCoordinates:(UILongPressGestureRecognizer *)sender {
CGPoint location = [sender locationInView:self.view];
NSLog(@"Tap at %1.0f, %1.0f", location.x, location.y);
}
UIWebView实际上将HTML渲染成UIView,具体来说,它可能会将可选择的文本渲染成UITextView,因此您需要尝试进入正确视图的委托方法。
这是一个应该有效的hack:
UITextViewDelegate
方法textViewDidChangeSelection:
以获取所选范围并与之交互。**步骤3和4的替代方法是使用KVO监听textView的selectedRange的更改。