UIPanGestureRecognizer不接受UIView目标

时间:2014-10-28 13:12:13

标签: ios uipangesturerecognizer

我有一个简单的演示应用程序,我试图动态添加一个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");
}

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

1 个答案:

答案 0 :(得分:1)

这是一个非常常见的问题,因为很容易被-initWithTarget:action:

中的“目标”一词误导

尝试将initWithTarget:textBG更改为initWithTarget:self,事情应该有效。

所以你的新代码行将如下所示:

self.panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(detectPan:)];

人们惹恼“目标”这个词的原因是因为他们认为“目标”是“我想用我的自定义代码定位的对象”(即“我想在屏幕上拖动的UIView”) ),相反,他们应该将UIPanGestureRecognizer的目标想象为“当前包含我想要在屏幕上拖动的对象的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) |     |
|    |          |     |
|    ------------     |
|                     |
-----------------------

因此,在您的示例中,您的应用程序崩溃是因为您将textBG设置为目标,并将detectPan设置为操作,这非常重要,“当在textBG对象中检测到平移手势时,调用detectPan方法textBG对象“,但是你没有对textBG对象有一个detectPan方法,你只有一个存在于textBG父级内的detectPan方法(即”self“)。这就是为什么在这种情况下你将无法识别的选择器发送到实例错误的原因,因为你的程序找不到与你的textBG对象相关联的-detectPan:方法。

希望这有帮助!