objective-c - 自定义 UIGestureRecognizer : selector does not receive UIGestureRecognizerStateBegan

标签 objective-c ios xcode uigesturerecognizer

我正在实现自定义 UIGestureRecognizer。为简单起见,假设它识别包含 >1 次触摸的手势。

这是 Gesture.m:

#import "Gesture.h"
#import <UIKit/UIGestureRecognizerSubclass.h>

#define SHOW printf("%s %d %d %d\n", __FUNCTION__, self.state, touches.count, self.numberOfTouches)

@implementation Gesture

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  SHOW;
  if (self.numberOfTouches==1) return;
  self.state = UIGestureRecognizerStateBegan;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
  SHOW;
  if (self.numberOfTouches==1) return;
  self.state = UIGestureRecognizerStateChanged;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  SHOW;
  if (self.numberOfTouches==1) return;
  self.state = UIGestureRecognizerStateEnded;
}
@end

这是一个选择器:

- (IBAction)handleGesture:(Gesture *)recognizer {
  printf("%s %d\n", __FUNCTION__, recognizer.state);
}

这是一个输出:

-[Gesture touchesBegan:withEvent:] 0 1 1  // 1st touch began
-[Gesture touchesMoved:withEvent:] 0 1 1
-[Gesture touchesMoved:withEvent:] 0 1 1
-[Gesture touchesMoved:withEvent:] 0 1 1
-[Gesture touchesBegan:withEvent:] 0 1 2  // 2nd touch began
-[Gesture touchesMoved:withEvent:] 1 1 2  // Gesture.state==UIGestureRecognizerStateBegan but selector was not called
-[ViewController handleGesture:] 2        // UIGestureRecognizerStateChanged received.
-[Gesture touchesMoved:withEvent:] 2 2 2
-[ViewController handleGesture:] 2
-[Gesture touchesMoved:withEvent:] 2 2 2
-[ViewController handleGesture:] 2
-[Gesture touchesMoved:withEvent:] 2 2 2
-[ViewController handleGesture:] 3        // UIGestureRecognizerStateEnded received.

为什么选择器没有收到 UIGestureRecognizerStateBegan?

最佳答案

这对我来说不是特别明显,但规则似乎是:

  • 通过 touchesBegan:... 发送给您的所有触摸随后都被视为属于您,除非您将状态设置为 UIGestureRecognizerStateFailedUIGestureRecognizerStateEndedUIGestureRecognizerStateCancelled;
  • 如果您改为转换到 UIGestureRecognizerStateBegan,则手势识别器会将其发布,然后在现在分配的触摸时自动生成UIGestureRecognizerStateChanged给你搬家。

因此,您不应该为自己设置 UIGestureRecognizerStateChanged — 只需跟踪触摸并正确发布开始、结束、失败和取消即可。

在你的情况下,我认为你只需要删除 touchesMoved:... 中的状态集。

(另外:以上内容适用于 iOS 5 和 6;在 4 下,行为稍微更微妙。要在所有三个版本下工作,请使用类似 if(self.state == UIGestureRecognizerStateBegan) self.state 的结构= UIGestureRecognizerStateChanged; 当你知道你的属性已经改变时)

关于objective-c - 自定义 UIGestureRecognizer : selector does not receive UIGestureRecognizerStateBegan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12334433/

相关文章:

iphone - 未调用完成 block 。如何检查有效性?

ios - 控制可能到达结束非空函数

ios - 使用swiftyjson库swift的嵌套Json数据获取和追加问题

ios - 更改 UIView 的边界并让 UICollisionBehavior 对其使用react

ios - XCode 5.1 的 Cocoapods 错误

iphone - 像 iPhone AppStore iOS 6 详细 View 中的选项卡(详细信息、评论、相关)

objective-c - 在 Objective-C 中更改 block 内的值

iphone - 将自定义 View Controller 添加到 Storyboard

ios - 使用 Swift 3 在 iOS 中替代 Android ViewPager

xcode - 我不是团队代理,如何使用开发者 ID 签署 mac 应用程序?