3

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最初可能会应用默认的缩放比例,但我找不到这个值对应的值。

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

有谁知道我做错了什么?

谢谢,

4

1 回答 1

3

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

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

- (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-01-15T06:52:48.880 回答