如何在iOS 7中仅针对一个视图禁用后退手势

Roh*_*mar 5 back gesture ios7

我正在尝试使用以下代码集为视图控制器禁用后退手势.

FirstViewController.m,我正在设置代表interactivePopGestureRecognizer

- (void) viewWillLoad {

    // Other stuff..
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
Run Code Online (Sandbox Code Playgroud)

然后实现该<UIGestureRecognizerDelegate>方法并返回NO.

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

     return NO;
}
Run Code Online (Sandbox Code Playgroud)

在dealloc中,我将委托设置为nil.(我已在某处读过,在iOS 7中,您必须手动将委托设置为nil)

- (void)dealloc {

    self.navigationController.delegate = nil;
    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}
Run Code Online (Sandbox Code Playgroud)

这适用于FirstViewController.但是,当我推动SecondViewController这个时,手势也不起作用.如何才能在FirstViewController中禁用手势?

此外,当我弹出FirstViewControllerRootViewController然后尝试FirstViewController再次推送时,我得到对象解除分配错误:

[FirstViewController gestureRecognizer:shouldReceiveTouch:]: message sent to deallocated instance 0x14ed0280
Run Code Online (Sandbox Code Playgroud)

为什么除了将委托设置为nil之外我还需要做什么?或者我把它放在错误的地方?

nul*_*ull 24

在FirstViewController中尝试以下未经测试的代码:

-(void) viewWillAppear:(BOOL)animated 
{
    [super viewWillAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

-(void) viewWillDisappear:(BOOL)animated 
{
    [super viewWillDisappear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}
Run Code Online (Sandbox Code Playgroud)

  • 添加此代码时,当我尝试执行后退手势时,禁用SecondViewController内所有元素的交互.这是为什么?? (2认同)
  • 您确定要实现视图>将<消失而不是viewDidDisappear吗?如果您在viewDidDisappear中重新启用手势识别器,则self.navigationController将为nil,因此无法重新启用它. (2认同)

Joh*_*ers 16

我最初将这些答案放在接受答案之下的评论中,但我觉得这需要作为获得更多可见性的答案.

通常情况下,您会发现接受的答案不起作用.这是因为viewWillAppear:可以在将视图添加到导航控制器的视图层次结构之前调用,因此self.navigationController也是如此nil.因此,在某些情况下可能不会禁用interactivePopGestureRecognizer.你最好viewDidAppear:不要再打电话了.

这里的代码将起作用(假设您的视图控制器已正确添加到导航控制器的视图层次结构中):

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[[self navigationController] interactivePopGestureRecognizer] setEnabled:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[[self navigationController] interactivePopGestureRecognizer] setEnabled:YES];
}
Run Code Online (Sandbox Code Playgroud)