【问题标题】:UIWebView, Zoom & elementFromPointUIWebView、缩放和 elementFromPoint
【发布时间】:2013-01-15 03:20:07
【问题描述】:

UIWebView 中,当我长按它时,我需要访问 DOM 元素的属性(来自 SVG 图)。为此,我添加了UILongPressGestureRecognizer,如下所示:

UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action: @selector(longPress:)];
[self.webView addGestureRecognizer: longPress];

当我长按视图时,处理程序被调用,我从中调用一个 JS 函数:

- (void) longPress: (UIGestureRecognizer *) gesture {
    CGPoint curCoords = [gesture locationInView:self.webView];

    if (!CGPointEqualToPoint(curCoords, self.lastLongPress)) {
        self.lastLongPress = curCoords;
        [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"longPress(%f, %f)", curCoords.x, curCoords.y]];
    }
}

这是我的 JS 处理程序:

function longPress(x, y) {

    x = x + window.pageXOffset;
    y = y + window.pageYOffset;

    var element = svgDocument.elementFromPoint(x, y);                                                                                                                                                                                                                           
    alert(element.localName + ' ' + x + ' ' + y + ' ' + window.innerWidth + ' ' +  window.innerHeight);
}

但是,UIWebView 坐标似乎是 != 来自 DOM 坐标(我单击的位置与警报中显示的 localName 不对应)。我设法弄清楚UIWebView 坐标和 JS 坐标之间存在 +/- 1.4 倍(通过单击屏幕右下角并将这些值与window.innder{Width,Height} 进行比较。

我的猜测是UIWebView 最初可能会应用默认缩放比例,但我找不到这个值对应的值。

此外,当用户实际缩放/移动页面时,我还需要一种方法来完成这项工作。

有人知道我做错了吗?

谢谢,

【问题讨论】:

    标签: javascript ios objective-c events uiwebview


    【解决方案1】:

    好的,我终于找到问题所在了。

    它来自缩放比例,这是我设法修复它的方法:

    - (void) longPress: (UIGestureRecognizer *) gesture {
        int displayWidth = [[self.webView stringByEvaluatingJavaScriptFromString:@"window.innerWidth"] intValue];
        CGFloat scale = self.webView.frame.size.width / displayWidth;
    
        CGPoint curCoords = [gesture locationInView:self.webView];
    
        curCoords.x /= scale;
        curCoords.y /= scale;
    
        if (!CGPointEqualToPoint(curCoords, self.lastLongPress)) {
            self.lastLongPress = curCoords;
    
            [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"longPress(%f, %f)", curCoords.x, curCoords.y]];
        }
    }
    

    还有 JS 处理程序:

    function longPress(x, y) {
        var e = svgDocument.elementFromPoint(x, y);
    
        alert('Youhouu ' + e.localName);
    }
    

    似乎不需要添加 pageOffset,因为现在 UIWebView 会自动添加它(我相信来自 iOS 5)。

    干杯,

    【讨论】:

      猜你喜欢
      • 2013-06-03
      • 2012-07-25
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多