2010-08-30 126 views
0

我試過下面的代碼,但它不起作用。它應該如何修改?如何獲得觸摸的觸摸位置開始功能

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    location = [touches locationInView:self]; 
} 

在我有這樣定義的位置的.h文件:

CGPoint location; 

回答

1

(NSSet *)touches會給你的屏幕上的所有當前觸摸。你需要每次觸摸這組數據並獲得它的座標。

這些觸摸是UITouch類的成員。看看UITouch class reference

,例如,你會怎麼做:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
    for (UITouch *touch in touches) { 
     CGPoint location = [touch locationInView:self]; 

     // Do something with this location 
     // If you want to check if it was on a specific area of the screen for example 
     if (CGRectContainsPoint(myDefinedRect, location)) { 
      // The touch is inside the rect, do something with it 
      // ... 
      // If one touch inside the rect is enough, break the loop 
      break; 
     } 
    } 
} 

乾杯!

+0

有沒有辦法直接訪問第一次觸摸,以便不需要使用for循環? – 2010-08-30 01:08:35

+1

您可以在for循環結束時設置一箇中斷,使其只運行一次。或者您可以按照@Vladimir的建議獲取anyObject。 – vfn 2010-08-30 01:12:18