5

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

4

3 回答 3

14

使用 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);
}

示例项目

于 2013-07-18T04:05:31.437 回答
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 Class Reference

于 2013-07-18T04:13:11.043 回答
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:触发,以及在触摸结束时触发(即抬起手指)。

您也可以使用 a 来执行此操作UIGestureRecognizer,这在许多情况下更实用。

于 2013-07-18T04:02:48.200 回答