2013-07-18 98 views

回答

13

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

触摸启动时触发此事件。

使用手势

注册您的UITapGestureRecognizer在viewDidLoad:方法

- (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); 
} 

Sample Project

+0

从你给出的第一种方法开始,使用触摸开始,我怎样才能使x和y位置的全局变量? – AwesomeTN

+0

在你的.h文件中创建一个CGPoint变量,并在上面的方法中指定它 – icodebuster

+0

触动开始很好,但我无法触摸已着手工作,几乎不是完全一样的东西? – AwesomeTN

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来做到这一点,这在很多情况下更实用。

+0

我c/p这到我的视图控制器,我得到了与NSLog的错误,但它通过将字符串更改为NSSringFromCGPoint解决。但我仍然没有收到控制台中的任何东西,我错过了什么?感谢您的帮助 – AwesomeTN

+0

您不应该添加任何额外的代码来完成此项工作。其他东西是否可以捕获触摸事件(例如,是否有像按钮这样的子视图可以阻止触摸进入viewController的视图)? – Ander

+0

本质上,添加到viewController的'self.view'中的任何视图都没有'.userInteractionEnabled = NO'会捕获触摸并阻止它进入上面答案中给出的方法。 – Ander

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