是否可以获取触摸的x和y坐标?

6

是否可以获取触摸的x和y坐标?如果可以,能否提供一个非常简单的示例,仅将坐标记录到控制台中。


3
你有阅读过UITouch类的参考文档吗? - rdelmar
3个回答

15

使用touchesBegan事件

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    NSLog(@"Touch x : %f y : %f", touchPoint.x, touchPoint.y);
}

当触控开始时,将触发此事件。

使用手势

viewDidLoad:方法中注册您的UITapGestureRecognizer。

- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGestureRecognizer:)];
    [self.view setUserInteractionEnabled:YES];
    [self.view addGestureRecognizer:tapGesture];
}

设置tapGestureRecognizer函数

// Tap GestureRecognizer function
- (void)tapGestureRecognizer:(UIGestureRecognizer *)recognizer {
    CGPoint tappedPoint = [recognizer locationInView:self.view];
    CGFloat xCoordinate = tappedPoint.x;
    CGFloat yCoordinate = tappedPoint.y;

    NSLog(@"Touch Using UITapGestureRecognizer x : %f y : %f", xCoordinate, yCoordinate);
}

示例项目


根据您提供的第一种方法,使用touches began,我如何将x和y位置变成全局变量? - AwesomeTN
在你的.h文件中创建一个CGPoint变量,并在上述方法中进行赋值。 - icodebuster
触摸开始工作得很好,但我无法让touchesEnded起作用,它不是几乎完全相同的东西吗? - AwesomeTN

2
首先,您需要将手势识别器添加到您想要的视图中。
UITapGestureRecognizer *myTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTapRecognizer:)];
[self.myView setUserInteractionEnabled:YES];
[self.myView addGestureRecognizer:myTap];

然后在手势识别器方法中,您调用locationInView:

- (void)myTapRecognizer:(UIGestureRecognizer *)recognizer
{
    CGPoint tappedPoint = [recognizer locationInView:self.myView];
    CGFloat xCoordinate = tappedPoint.x;
    CGFloat yCoordinate = tappedPoint.y;
}

你可能想要看一下苹果公司的UIGestureRecognizer类参考文档


0

这是一个非常基本的示例(将其放置在您的视图控制器中):

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self.view];
    NSLog(@"%@", NSStringFromCGPoint(currentPoint));
}

每次触摸移动时都会触发此操作。您还可以使用touchesBegan:withEvent:,它在触摸开始时触发,并且touchesEnded:withEvent:在触摸结束时触发(即手指抬起)。
您还可以使用UIGestureRecognizer来实现这一功能,在许多情况下更为实用。

我将这段代码复制粘贴到我的视图控制器中,NSLog出现了错误,但通过将字符串更改为NSSringFromCGPoint进行修复。但是,我仍然没有在控制台中收到任何内容,我是否遗漏了什么?感谢您的帮助。 - AwesomeTN
你不应该添加任何额外的代码来使其工作。是否有其他东西捕获了触摸事件(例如,是否有一个子视图,如按钮,可能会阻止触摸传递到viewController的视图)? - Ander
基本上,任何添加到viewController的self.view上的视图,如果没有设置.userInteractionEnabled = NO,都会捕获触摸事件并阻止其传递到上面给出的方法。 - Ander

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接