swift-自定义导航栏后侧滑返回功能失效解决办法(不用再添加侧滑手势)

从iOS7开始,系统为UINavigationController提供了一个interactivePopGestureRecognizer用于右滑返回(pop),但是如果自定了当前视图控制器leftBarButtonItem,该手势就失效了。

解决方法:自定义UINavigationController并实现其代理方法重新设置侧滑手势的代理。

具体代码如下:

class BaseNavigationController: UINavigationController ,UINavigationControllerDelegate {
    
    var popDelegate: UIGestureRecognizerDelegate?
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.popDelegate = self.interactivePopGestureRecognizer?.delegate
        
        self.delegate = self
    }
    
    // MARK: - UINavigationControllerDelegate方法
    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {

        if viewController == self.viewControllers[0] {
            
            self.interactivePopGestureRecognizer!.delegate = self.popDelegate
        }
        else {
            self.interactivePopGestureRecognizer!.delegate = nil
        }
    }

你可能感兴趣的:(swift-自定义导航栏后侧滑返回功能失效解决办法(不用再添加侧滑手势))