iOS如何支持手势返回

传统做法是在viewcontroller上设置navigationController的interactivePopGesturerecovnezer,但是bug很多,推荐如下,在nav controller上的做法:

class C4MVTNavigationController: UINavigationController {

    // MARK: - Property
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return self.visibleViewController?.supportedInterfaceOrientations ?? .portrait
    }

    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return self.visibleViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }

    // MARK: - Funtions
    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
    }
}

extension C4MVTNavigationController: UINavigationControllerDelegate {

    func navigationController(_ navigationController: UINavigationController,
                              didShow viewController: UIViewController,
                              animated: Bool) {
        let isRoot = ( viewController == navigationController.viewControllers.first )
        var enable = !isRoot
        if enable {
            if let vc = viewController as? C4MVTBaseController {
                enable = vc.needPopGesture
            }
        }
        if enable {
            navigationController.interactivePopGestureRecognizer?.isEnabled = !isRoot
            navigationController.interactivePopGestureRecognizer?.delegate = self
        } else {
            navigationController.interactivePopGestureRecognizer?.isEnabled = false
            navigationController.interactivePopGestureRecognizer?.delegate = nil
        }
    }

}

extension C4MVTNavigationController: UIGestureRecognizerDelegate {

    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

}

 

完整代码可以参考我的 iOSMVT 项目。

Leave a Reply

Your email address will not be published.