OStack程序员社区-中国程序员成长平台

标题: ios - UITapGestureRecognizer 在关闭 viewController 后导致崩溃 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 00:41
标题: ios - UITapGestureRecognizer 在关闭 viewController 后导致崩溃

尝试将 UITapGestureRecognizer 实现到表单模态视图 Controller 。 如果用户在表单之外触摸,表单应该关闭,这样代码就可以正常工作了。

问题是如果我手动关闭表单并尝试触摸任何视点,它仍然会尝试调用 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)viewDidAppearBOOL)animated
{
    // gesture recognizer to cancel screen
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self actionselector(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)handleTapBehindUITapGestureRecognizer *)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];
        }
    }
}

为什么在我关闭 View Controller 后仍然调用 handleTapBehind:?我怎样才能解决这个问题?



Best Answer-推荐答案


给窗口添加手势识别器:

[self.view.window addGestureRecognizer:recognizer];

并将目标设置为您的 Controller ;

因此,当您的 Controller 关闭时 - 它已被释放,但手势识别器仍然存在。当它触发时,它会尝试向您的 Controller 发送操作,但该 Controller 已经不存在了。

因此,您应该将识别器添加到 Controller 的 View 中或在 viewWillDissaper 方法中将其删除。

关于ios - UITapGestureRecognizer 在关闭 viewController 后导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14588061/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4