【问题标题】:iPhone: detect two finger touchiPhone:检测两根手指触摸
【发布时间】:2011-02-03 20:10:02
【问题描述】:

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

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

但如果我握住一根手指然后用另一根手指触摸屏幕,则此代码不起作用。如何实施?很难吗?

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    确保 UIView 有multipleTouchEnabled=YES,默认为NO

    编辑:我知道问题出在哪里。在 touchesBegan:withEvent: 中,你只会得到新的接触。你不会得到所有的主动接触。如果可能的话,您不太可能同时开始多于一次触摸。要检查是否有多个活动的触摸 int 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] 用于测试目的。
    • 你在哪里添加 [self.view setMultipleTouchEnabled:YES]?
    • 感谢重播。我在 viewDidLoad 中添加 [self.view setMultipleTouchEnabled:YES]
    • 这是正确的地方。 self.view(控制器的视图)是接收触摸的那个吗?有子视图吗?
    • 不,我不使用任何其他子视图。您可以从dl.dropbox.com/u/11760459/touch.zip 下载简单的项目。问题:然后我握住一根手指并触摸另一根手指 touchesBegan 仅针对一根手指触发。
    【解决方案2】:

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

    例如,如果您在 UIScroolView 中,那么您可以获取 sec touch:
    - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView;

    【讨论】:

    • 谢谢,但我不需要缩放。我只想用 touchesBegan、touchesMoved、touchesEnded 来实现所有东西。这个方法返回 UIView 所以它不适合我。
    【解决方案3】:
    - (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];
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-08
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-28
      • 2015-06-14
      相关资源
      最近更新 更多