gpt4 book ai didi

ios - 如何在 UIWebView 中获取触摸的 (X,Y) 坐标

转载 作者:可可西里 更新时间:2023-11-01 03:57:06 24 4
gpt4 key购买 nike

我有一个显示生成的 html 表格的 UIWebView。当用户点击 html 表格中的单元格时,我的应用需要知道他们点击了哪个单元格,以及点击位置的 (x,y) 坐标,以便我可以在该点显示弹出窗口。

我已经在我的 UIWebView 委托(delegate)中实现了 shouldStartLoadWithRequest。在我的网页中,我嵌入了捕获触摸事件的 javascript 代码,并在 URL 请求中传递应该是触摸点的 (x,y) 坐标,如下所示:

var x, y;

function init()
{
// Add an event listener for touch events - set x and y to the coordinate of the touch point
document.addEventListener('touchstart', function(event) {
x = event.touches[0].clientX;
y = event.touches[0].clientY;
}, false);
}

function cellTapped(event)
{
window.location.href="file://myapp/dostuff?x=" + x + "&y=" + y;
}

在我的 html 表格中,每个单元格都有一个调用 cellTapped() 的 onclick 事件:

<td onclick="cellTapped(event)">...</td>

因此,每当用户触摸 UIWebView 中的任何位置时,我都会获取触摸点的坐标,并将其保存在 x 和 y 中。如果它们在其中一个表格单元格内触摸,我会收到触摸事件(设置 x 和 y),然后调用 cellTapped() 并设置 window.location.href,将 (x,y) 坐标传递到我的应用程序中。

这一切都很完美。除非用户缩放或滚动 UIWebView。当它们缩放或滚动时,我从 event.touches[0].clientX 和 event.touches[0].clientY 获得的 x 和 y 坐标会偏离一些不同数量的像素(随缩放量和方式而变化) Web View 向上/向下或向左/向右滚动。

有什么方法可以确定 Web View 的缩放比例和滚动位置,以便我可以相应地调整我的 x 和 y 坐标? UIScrollView 的 zoomScalecontentOffset 属性似乎没有在 UIWebView 中公开。

最佳答案

使用 UIGestureRecognizerDelegate 方法:

在声明文件(即您的 .h 文件)中添加 UIGestureRecognizerDelegate

第1步:只需设置gestureRecognizer的委托(delegate):(在.m文件中)

UITapGestureRecognizer *webViewTapped = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
webViewTapped.numberOfTapsRequired = 1;
webViewTapped.delegate = self;
[webView addGestureRecognizer:webViewTapped];
[webViewTapped release];

第 2 步:覆盖此函数:(在 .m 文件中)

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}

第 3 步:现在实现 tapAction 函数:

- (void)tapAction:(UITapGestureRecognizer *)sender
{
CGPoint point = [sender locationInView:self.view]; // get x and y from here
}

关于ios - 如何在 UIWebView 中获取触摸的 (X,Y) 坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18210745/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com