解除viewController后,UITapGestureRecognizer会导致崩溃

时间:2013-01-29 16:56:30

标签: ios objective-c ipad

尝试将UITapGestureRecognizer实现到表单模式viewcontroller。 如果用户触摸表单外部,表单应该被忽略,这样代码就可以正常工作。

问题是如果我手动关闭表单并尝试触摸视图中的任何一点,它仍会尝试调用UITapGestureRecognizer方法和应用程序崩溃。

Error ::
    -[xxxxView handleTapBehind:]: message sent to deallocated instance



-(void)done
{
    [self.navigationController popViewControllerAnimated:YES];
        //send notification that folder has been created
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDetails" object:nil];
}
-(void)viewDidAppear:(BOOL)animated
{
    // gesture recognizer to cancel screen
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapBehind:)];
    [recognizer setNumberOfTapsRequired:1];
    recognizer.cancelsTouchesInView = NO; //So the user can still interact with controls in the modal view
    [self.view.window addGestureRecognizer:recognizer];

}

- (void)handleTapBehind:(UITapGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        CGPoint location = [sender locationInView:nil]; //Passing nil gives us coordinates in the window

        //Then we convert the tap's location into the local view's coordinate system, and test to see if it's in or outside. If outside, dismiss the view.

        if (![self.view pointInside:[self.view convertPoint:location fromView:self.view.window] withEvent:nil])
        {
            // Remove the recognizer first so it's view.window is valid.
            [self.view.window removeGestureRecognizer:sender];
            [self dismissModalViewControllerAnimated:YES];
        }
    }
}

为什么在解除viewcontroller后仍然调用handleTapBehind:?我怎样才能解决这个问题?

3 个答案:

答案 0 :(得分:4)

您将手势识别器添加到窗口:

[self.view.window addGestureRecognizer:recognizer];

并将目标设定为您的控制器;

因此,当您的控制器关闭时 - 它已被释放,但手势识别器仍然存在。当它触发时,它会尝试向你的控制器发送动作,而这个动作已经不存在了。

因此,您应该将识别器添加到控制器的视图中,或者在viewWillDissaper方法中删除它。

答案 1 :(得分:0)

尝试使用手势识别器的委托方法,在手动关闭vc并在shouldReceiveTouch中放置一个标志:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
   if(flag)
   {
      return NO;
   }
   return YES;
}

不要忘记将委托设置为当前的viewcontroller。此外,您现在可以删除行[self.view.window removeGestureRecognizer:sender];

答案 2 :(得分:0)

我想从@mikhail的回答中添加代码

 (UITapGestureRecognizer *)senderTap

-(void)viewWillDisappear:(BOOL)animated{

     [self.view.window removeGestureRecognizer:senderTap];
}

在我的代码中,当调用ViewDidAppear时,我在选择器方法中捕获UITapGestureRecognizer(sender)。