UINavigationController 的 interactivePopGestureRecognizer 属性为返回手势。设置手势的 delegate,手动管理返回手势。当 UINavigationController 没有或只有一个子控制器时,返回手势不能响应,否则会出现奇怪的现象。自定义 currentNotRootVC 属性,记录当前的非根子控制器(只有一个子控制器时,此子控制器为根子控制器,root view controller)。设置 UINavigationController 的 delegate,通过 UINavigationControllerDelegate 的方法,更新 currentNotRootVC。代码示例如下
import UIKit
class NavigationController: UINavigationController, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
// Current child view controller, but not root view controller
private var currentNotRootVC: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
interactivePopGestureRecognizer?.delegate = self
}
// MARK: - UINavigationControllerDelegate
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
currentNotRootVC = viewControllers.count <= 1 ? nil : viewController
/*
switch viewController {
case is SomeVCClassForbidPopGesture:
interactivePopGestureRecognizer?.isEnabled = false
default:
interactivePopGestureRecognizer?.isEnabled = true
}
*/
}
// MARK: - UIGestureRecognizerDelegate
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if interactivePopGestureRecognizer == gestureRecognizer {
// Begin to pop only when top view controller is current child view controller but not root view controller
return currentNotRootVC == topViewController
}
return true
}
}
如果有部分控制器不允许返回手势(例如编辑信息,退出页面需要确认),则在func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool)
方法中,加入对 viewController 的判断,开启或禁用返回手势。
下载说明
☉本站所有源码和资源均由站长亲自测试-绝对保证都可以架设,运营!
☉如源码和资源有损坏或所有链接均不能下载,请告知管理员,
☉本站软件和源码大部分为站长独资,资源购买和收集,放心下载!
☉唯一站长QQ:1004003180 [人格担保-本站注重诚信!]
☉购买建议E-mail:1004003180@qq.com 源码收购 E-mail:1004003180@qq.com
☉本站文件解压密码 【文章内都自带解压密码,每个密码不同!】