现象描述
实际开发过程中,难免会重写UINavigationController的左返回按钮,然后就导致了系统默认的右滑返回失效。
如何处理
直接先上关键代码:
public class DZBaseNavigationController: UINavigationController {
public override func viewDidLoad()
{
super.viewDidLoad()
//处理右滑返回手势
let selector = NSSelectorFromString("interactivePopGestureRecognizer")
if self.responds(to: selector){
self.interactivePopGestureRecognizer?.delegate = self
self.delegate = self
}
}
//重写父类方法
public override func pushViewController(_ viewController: UIViewController, animated: Bool)
{
//处理右滑返回手势
let selector = NSSelectorFromString("interactivePopGestureRecognizer")
if self.responds(to: selector){
self.interactivePopGestureRecognizer?.isEnabled = false
}
super.pushViewController(viewController, animated: animated)
}
}
extension DZBaseNavigationController:UINavigationControllerDelegate,UIGestureRecognizerDelegate{
//处理右滑返回手势
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
return true
}
//DZBaseViewController为项目中所有UIViewController的子类,也就是目前项目中所有的UIViewController都是用的DZBaseViewController,DZBaseViewController里可以添加一些基础属性,比如: ///是否能右滑返回 var isCanGestureBack:Bool = true
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
let selector = NSSelectorFromString("interactivePopGestureRecognizer")
let currentvc = self.topViewController
if self.responds(to: selector){
if gestureRecognizer == self.interactivePopGestureRecognizer{
if self.viewControllers.count == 1{
return false
}else{
if let vc = currentvc as? DZBaseViewController{
if vc.isCanGestureBack == false{
return false
}else{
return true
}
}else{
return false
}
}
}
}
return false
}
public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
let selector = NSSelectorFromString("interactivePopGestureRecognizer")
if self.responds(to: selector){
self.interactivePopGestureRecognizer?.isEnabled = true;
}
}
}
备注:
关键字为:
interactivePopGestureRecognizer
所有的逻辑都在DZBaseNavigationController里,DZBaseViewController继承UIViewController,isCanGestureBack参数可以在具体某个不需要手势右滑返回的UIViewController中设置为:false
class DZBaseViewController: UIViewController {
///是否能右滑返回
var isCanGestureBack:Bool = true
}
比如某个UIViewController不需要支持右滑返回:
class DZPasswordLoginVC: DZBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.isCanGestureBack = false
}
}