方法一:
1.在ViewDidLoad
方法中添加中划手势
// 获取屏幕边缘手势识别器
UIScreenEdgePanGestureRecognizer *gesture = (UIScreenEdgePanGestureRecognizer *)self.interactivePopGestureRecognizer;
// 先禁止系统的左侧滑手势
gesture.enabled = NO;
// 利用KVC强制获取手势数组
// 利用运行时查看私有属性
NSMutableArray *targets = [gesture valueForKeyPath:@"_targets"];
// 获取这个这个手势对象
id gestureTarget = [targets firstObject];
// 利用KVC获取手势的私有属性target
id target = [gestureTarget valueForKeyPath:@"_target"];
// 创建滑动手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:@selector(handleNavigationTransition:)];
// 设置自定义的手势代理为控制器,这样自定义的手势就会调用代理的这个方法`gestureRecognizerShouldBegin:`
pan.delegate = self;
// 添加自定义手势到手势识别器的View中
[gesture.view addGestureRecognizer:pan];
添加上面的方法后,就可以实现中间和侧滑都可以返回的功能,但是回到导航控制器的跟界面,任然可以中划和侧滑,并且跳转出现假死状态;解决方案很简单,只要是导航控制器的跟控制器,我们过滤掉这个侧滑和中划功能;
2.遵守代理协议,实现代理的方法
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
// 这里有两个条件不允许手势执行:1、当前控制器为根控制器;2、如果这个push、pop动画正在执行(私有属性)
return self.viewControllers.count != 1 && ![[self valueForKey:@"_isTransitioning"] boolValue];
}
方法二:
1.设置导航控制器的代理为自己,遵守导航控制器代理协议
@interface DXNavigationController ()<UINavigationControllerDelegate>
self.delegate = self;
2.调用导航控制器的代理方法
// 导航控制器加载完毕一个View的时候就会调用这个方法
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if (viewController == self.childViewControllers[0])
{
[self addGesture:nil];
}else{
[self addGesture:@selector(handleNavigationTransition:)];
}
}
2.1添加自定义手势
- (void)addGesture:(SEL)action
{
UIScreenEdgePanGestureRecognizer *gesture = (UIScreenEdgePanGestureRecognizer *)self.interactivePopGestureRecognizer;
gesture.enabled = NO;
NSMutableArray *targets = [gesture valueForKeyPath:@"_targets"];
id gestureTarget = [targets firstObject];
id target = [gestureTarget valueForKeyPath:@"_target"];
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:action];
[gesture.view addGestureRecognizer:pan];
}
效果图: