No Swipe Back when hiding Navigation Bar in UINavigationController

前端 未结 18 695
生来不讨喜
生来不讨喜 2020-12-04 06:34

I love the swipe pack thats inherited from embedding your views in a UINavigationController. Unfortunately i cannot seem to find a way to hide the Naviga

18条回答
  •  清歌不尽
    2020-12-04 07:00

    Simple, no side-effect Answer

    While most answers here are good, they seemingly have unintended side-effects (app breaking) or are verbose.

    The most simple yet functional solution I could come up with was the following:

    In the ViewController that you are hiding the navigationBar,

    class MyNoNavBarViewController: UIViewController {
        
        // needed for reference when leaving this view controller
        var initialInteractivePopGestureRecognizerDelegate: UIGestureRecognizerDelegate?
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            // we will need a reference to the initial delegate so that when we push or pop.. 
            // ..this view controller we can appropriately assign back the original delegate
            initialInteractivePopGestureRecognizerDelegate = self.navigationController?.interactivePopGestureRecognizer?.delegate
        }
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(true)
    
            // we must set the delegate to nil whether we are popping or pushing to..
            // ..this view controller, thus we set it in viewWillAppear()
            self.navigationController?.interactivePopGestureRecognizer?.delegate = nil
        }
    
        override func viewWillDisappear(_ animated: Bool) {
            super.viewWillDisappear(true)
    
            // and every time we leave this view controller we must set the delegate back..
            // ..to what it was originally
            self.navigationController?.interactivePopGestureRecognizer?.delegate = initialInteractivePopGestureRecognizerDelegate
        }
    }
    

    Other answers have suggested merely setting the delegate to nil. Swiping backwards to the initial view controller on the navigation stack results in all gestures to be disabled. Some sort of oversight, perhaps, of the UIKit/UIGesture devs.

    As well, some answers here that I have implemented resulted in non-standard apple navigation behaviour (specifically, allowing for the ability to scroll up or down while also swiping backwards). These answers also seem a bit verbose and in some cases incomplete.

提交回复
热议问题