Ios UIPangESTURE识别器不接受UIView目标

Ios UIPangESTURE识别器不接受UIView目标,ios,uipangesturerecognizer,Ios,Uipangesturerecognizer,我有一个简单的演示应用程序,其中我尝试动态添加一个UITextView,并在其后面直接添加一个UIView(作为背景)。但每次我编译和测试平移手势时,都会出现以下错误: -[UIView detectPan:]:无法识别的选择器发送到实例0x17e7fc30 以下是我的示例代码,我在其中创建UIView并分配UIPanGesture: CGRect textFieldFrame = CGRectMake(0, 44, 320, 44); // Create a TextField UIText

我有一个简单的演示应用程序,其中我尝试动态添加一个UITextView,并在其后面直接添加一个UIView(作为背景)。但每次我编译和测试平移手势时,都会出现以下错误:

-[UIView detectPan:]:无法识别的选择器发送到实例0x17e7fc30

以下是我的示例代码,我在其中创建UIView并分配UIPanGesture:

CGRect textFieldFrame = CGRectMake(0, 44, 320, 44);

// Create a TextField
UITextField *textField = [[UITextField alloc] initWithFrame:textFieldFrame];
textField.userInteractionEnabled = NO;
textField.layer.zPosition = 100001;
[self.view addSubview:textField];

// Create the Text Background View
UIView *textBG = [[UIView alloc] initWithFrame:textFieldFrame];
textBG.layer.zPosition = 100000;
[self.view addSubview:textBG];

self.panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:textBG action:@selector(detectPan:)];
还有我的detectPan方法:

-(void)detectPan:(UIPanGestureRecognizer *)gr {
    NSLog(@"inside detectPan");
}

在我的实现过程中是否缺少一些步骤?我发誓这种完全相同的方法在过去对我有效,但现在根本不起作用。非常混乱

这是一个非常常见的问题,因为在
-initWithTarget:action:

尝试将
initWithTarget:textBG
更改为
initWithTarget:self
,一切都应该正常

因此,您的新代码行将如下所示:

self.panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(detectPan:)];
人们之所以会被“target”这个词绊倒,是因为他们认为“target”是“我想用我的自定义代码作为目标的对象”(即“我想在屏幕上拖动的UIView”),而实际上,他们应该将UIPangestureRecognitor的目标视为“当前包含我要在屏幕上拖动的对象的UIView”,或者换句话说,“拥有我要用于计算平移手势平移的坐标空间的UIView”

像这样:

----------------------- | | | Containing UIView -|-----> "THE TARGET" | | The "target" owns the x,y coordinate space where the | ------------ | UIPanGestureRecognizer will calculate the movements of | | | | your "drag" or "pan" across the screen. | | UIView | | | | (textBG) | | | | | | | ------------ | | | ----------------------- ----------------------- | | |包含UIView-|------->“目标” ||“目标”拥有x,y坐标空间,其中 |--------------UIPangestureRecognitor将计算 || | |在屏幕上“拖动”或“平移”。 || UIView || ||(textBG)|| | | | | | ------------ | | | ----------------------- 因此,在您的示例中,您的应用程序正在崩溃,因为您将textBG设置为目标,detectPan设置为动作,这基本上是说“当在textBG对象中检测到平移手势时,请调用textBG对象的detectPan方法,但您在textBG对象上没有detectPan方法,您只有一个存在于textBG父对象中的detectPan方法(即“self”)。这就是为什么在这种情况下,将无法识别的选择器发送到实例错误的原因,因为您的程序找不到与textBG对象关联的-detectPan:方法


希望这有帮助

您是否向任何控件添加了手势?[self.view addgestureRecognitizer:self.panRecognitizer];