在iOS 7中,苹果增加了一个新的默认导航行为。你可以从屏幕的左边缘滑动回到导航堆栈。但在我的应用程序中,这种行为与我的自定义左侧菜单冲突。那么,是否有可能在UINavigationController中禁用这个新手势?


当前回答

这是Swift 3的方式

对我有用

    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

其他回答

只需从NavigationController中删除手势识别器。在iOS 8中工作。

if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
    [self.navigationController.view removeGestureRecognizer:self.navigationController.interactivePopGestureRecognizer];

所有这些解决方案都以一种他们不推荐的方式操纵苹果的手势识别器。我的一个朋友刚刚告诉我,有一个更好的解决方案:

[navigationController.interactivePopGestureRecognizer requireGestureRecognizerToFail: myPanGestureRecognizer];

其中myPanGestureRecognizer是你用来显示菜单的手势识别器。这样,当你按下一个新的导航控制器时,苹果的手势识别器就不会被重新打开,也不需要依赖黑客延迟,如果你的手机处于睡眠状态或负载过重,可能会过早触发。

把这个留在这里,因为我知道下次需要的时候我不会记得了,然后我就有了这个问题的解决方案。

它适用于我的大多数视图控制器。

self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

对于一些视图控制器,比如UIPageViewController,它并不是无效的。在UIPageViewController的pagecontentviewcontroller下面的代码为我工作。

override func viewDidLoad() {
   self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
   self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}
override func viewWillDisappear(_ animated: Bool) {
   self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
   self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
}

On UIGestureRecognizerDelegate,

func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
   if gestureRecognizer == self.navigationController?.interactivePopGestureRecognizer {
      return false
}
      return true
}

我的方法。一个手势识别器来统治它们:

class DisabledGestureViewController: UIViewController: UIGestureRecognizerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController!.interactivePopGestureRecognizer!.delegate = self
    }

    func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
        // Prevent going back to the previous view
        return !(navigationController!.topViewController is DisabledGestureViewController)
    }
}

重要:不要在导航堆栈的任何地方重置委托:navigationController!.interactivePopGestureRecognizer!.delegate = nil

没有一个给出的答案帮助我解决这个问题。在这里张贴我的答案;可能对某人有帮助

声明私有var popGesture: UIGestureRecognizer?作为视图控制器中的全局变量。然后在viewDidAppear和viewWillDisappear方法中实现代码

override func viewDidAppear(animated: Bool) {

    super.viewDidAppear(animated)

    if self.navigationController!.respondsToSelector(Selector("interactivePopGestureRecognizer")) {

        self.popGesture = navigationController!.interactivePopGestureRecognizer
        self.navigationController!.view.removeGestureRecognizer(navigationController!.interactivePopGestureRecognizer!)
    }
}


override func viewWillDisappear(animated: Bool) {

    super.viewWillDisappear(animated)

    if self.popGesture != nil {
        navigationController!.view.addGestureRecognizer(self.popGesture!)
    }
}

这将禁用滑动回iosv8。x起