2010-08-30 101 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