iPhone:检测两个手指触摸

9

我需要检测两个手指触摸事件。如果我同时用两个手指触摸屏幕,那么一切都正常。只需使用以下代码:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  UITouch *touch = [[touches allObjects] objectAtIndex:0];
  CGPoint point1 = [touch locationInView:self];
  CGPoint point2 ; 
  NSLog(@"First: %f %f", point1.x, point1.y) ; 
  if ([[touches allObjects] count] > 1) {
    UITouch *touch2 = [[touches allObjects] objectAtIndex:1];
    point2 = [touch2 locationInView:self];
    NSLog(@"Second: %f %f", point2.x, point2.y) ;   
  }
}   

但是如果我用一根手指按住屏幕,然后用另一根手指触摸屏幕时,这段代码就不起作用了。如何实现这个功能?难度大吗?
3个回答

19

确保UIView的multipleTouchEnabled=YES,默认值为NO

编辑:我知道问题出在哪里了。在touchesBegan:withEvent:中,你只会得到新的触摸。你不会得到所有活跃的触摸。很不可能,如果有可能的话,你会同时开始多个触摸。要检查是否有多个活动触摸在touchesBegan:中,请尝试以下操作:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

    if ([[event touchesForView:self] count] > 1) {
        NSLog(@"%d active touches",[[event touchesForView:self.view] count]) ;


    }
    [super touchesBegan:touches withEvent:event] ;
}

谢谢,但没有帮助。我已经在视图控制器中添加了以下代码:[self.view setMultipleTouchEnabled:YES];为了测试目的,我甚至在touchesBegan方法中添加了[self setMultipleTouchEnabled:YES]。 - kesrut
那是正确的位置。self.view(控制器的视图)是接收触摸的视图吗?有任何子视图吗? - fsaint
1
不,我没有使用任何其他的子视图。您可以从http://dl.dropbox.com/u/11760459/touch.zip下载简单的项目。问题是:当我按住一个手指并触摸另一个手指时,touchesBegan仅为一个手指触发。 - kesrut
小问题,但您可能希望将 touchesForView:self 更改为 touchesForView:self.view - akaru
方法touchesBegan:withEvent:处理视图和控制器中的事件。就像提出的问题一样,它是视图的方法。这不是错误,根据实现该方法的类,两种方法都是正确的。 - fsaint
显示剩余2条评论

1

接收事件的真正对象是什么?该对象可能会获取您的触摸事件,而不是基本的UIResponder。

例如,如果您在UIScroolView中,则可以在以下位置获取第二个触摸:
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView;


谢谢,但我不需要缩放。我只想用touchesBegan、touchesMoved和touchesEnded实现所有功能。这个方法返回UIView,所以对我来说不太合适。 - kesrut

0
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch1, *touch2;
    CGPoint    location1, location2;

    NSSet *allTouches = [event allTouches];
    touch1 = [[allTouches allObjects] objectAtIndex:0];
    location1 = [touch1 locationInView:self];

    if([allTouches count] > 1)
    {
        touch2 = [[allTouches allObjects] objectAtIndex:1];
        location2 = [touch2 locationInView:self];
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接