2013-07-18 101 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