ios - 如何将touchesBegan和touchesEnded限制为仅一次触摸?

标签 ios uigesturerecognizer

我有一个包含两个 subview 的 View :

  1. UIImageView
  2. 一个小的自定义 View ,就像一个带有可旋转指针的时钟。

我已经在自定义类似时钟 View 的touchesBegan和touchesMoved中编写了指针旋转的代码。

此自定义 View 放置在图像上,我已向 imageView 添加了两指缩放、旋转、平移手势。

现在我的问题是,每当我的两个手指之一触摸这个时钟 View 的手时,它们就会移动和旋转,这是我不想要的。

我只想限制他们的触摸,只有当我在他们身上做一个手指手势,而不是在其后面的图像上做两个手指手势时。

编辑:这是我添加手势的代码

UIPanGestureRecognizer *panGesture = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)] autorelease];
panGesture.maximumNumberOfTouches = 2;
panGesture.minimumNumberOfTouches = 2;
[self.imageView addGestureRecognizer:panGesture];

最佳答案

UIGestureRecognizer 的方法-(NSUInteger)numberOfTouches可以告诉您在您的 View 上进行了多少次触摸。还有这个Event Handling Guide可能会帮助你:)

另一种方法是 UITapGestureRecognizer ,可以使用 numberOfTouchesRequired 进行配置,以将一个识别器限制为特定数量的手指。

编辑

我建议您使用私有(private) BOOL,如果另一个手势识别器处于事件状态,它会锁定与其中一个手势识别器的交互。

借助 XCode 4 及更高版本中提供的新 LLVM 编译器,您可以在实现 (.m) 文件内的默认类别中声明 @private 变量:

@interface YourClassName() {
  @private:
    BOOL interactionLockedByPanRecognizer;
    BOOL interactionLockedByGestureRecognizer;
}
@end

@implementation YourClassName
  ... your code ...
@end

您处理平移交互的方法(我假设您最后会做某种动画来移动东西):

- (void)handlePan:(id)sender
{
  if (interactionLockedByGestureRecognizer) return;

  interactionLockedByPanRecognizer = YES;
  ... your code ...
  [UIView animateWithDuration:0.35 delay:0.0 options:UIViewAnimationCurveEaseOut
                 animations:^{
                   [[sender view] setCenter:CGPointMake(finalX, finalY)];
                 } 
                 completion:^( BOOL finished ) {
                   interactionLockedByPanRecognizer = NO;
                 }
 ];
}

现在,您只需检查 touchesBegantouchesMovedtouchesEnded 内部交互是否被 UIPanGestureRecognizer 锁定:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  if (interactionLockedByPanRecognizer) return;
  interactionLockedByGestureRecognizer = YES;
  ... your code ...
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
  if (interactionLockedByPanRecognizer) return;
  ... your code ...
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
  if (interactionLockedByPanRecognizer) return;
  ... your code ...
  interactionLockedByGestureRecognizer = NO;
}

关于ios - 如何将touchesBegan和touchesEnded限制为仅一次触摸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9818072/

相关文章:

ios - Swift 以编程方式启动 UILongPressGesture

ios - 检测小部件上任意位置的点击?

ios - 添加 UIGestureRecognizer 以从左向右滑动我的 View

iOS:在 cellForRowAtIndexPath 之外更改 UITableViewCell:

ios - UINavigationController 显示但没有后退按钮

ios - View 边界外的 subview 上的手势识别器

objective-c - UIMenuController 不响应第一次选择,只有第二次

ios - 从用户位置 ios 查找最近的注释?

ios - 应用拒绝说明 - 帮助了解实际问题是什么?

ios - 反转UITable行号从大到小(...5,4,3,2,1)