相关原理
iOS侧滑返回,有三种方案可以实现(只考虑iOS7以后)
-
开启使用系统自带的侧滑返回
self.navigationController.interactivePopGestureRecognizer.enabled = YES;
-
实现UINavigationViewController的代理方法,自定义动画对象和交互对象(即自定义转场动画)
有关的协议,有空研究下 UIViewControllerAnimatedTransitioning:遵从该协议的对象,即是我们自定义的动画; UIViewControllerInteractiveTransitioning:遵从该协议实现动画可交互性。 不过一般我们直接使用系统UIPercentDrivenInteractiveTransition类,不需自定义。 UIViewControllerContextTransitioning:遵从该协议,定义了转场时需要的元数据。一般不需自己定义。
-
利用系统自带的侧滑返回,替换掉系统自带的侧滑手势的委托对象
替换掉系统自带的侧滑手势的委托对象self.interactivePopGestureRecognizer.delegate = self;
手势的代理方法
#pragma mark - UIGestureRecognizerDelegate // 手势的代理方法 - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch: (UITouch *)touch { BOOL isShould = NO; if ( (self.childViewControllers.count<=1) ) { isShould = NO; }else { isShould = YES; } return isShould; }
我的实践
1.QqcNavigationController继承自UINavigationController,替换系统侧滑手势的委托对象
QqcNavigationController.h
#import <UIKit/UIKit.h>
@interface QqcNavigationController : UINavigationController
//是否开启滑动退场
@property(nonatomic, assign)BOOL isPanBackGestureEnable;
@end
QqcNavigationController.m
#import "QqcNavigationController.h"
@interface QqcNavigationController ()<UIGestureRecognizerDelegate>
@end
@implementation QqcNavigationController
#pragma mark - system framwork
- (void)viewDidLoad {
[super viewDidLoad];
self.interactivePopGestureRecognizer.delegate = self;
}
#pragma mark - property
- (void)setIsPanBackGestureEnable:(BOOL)isPanBackGestureEnable {
_isPanBackGestureEnable = isPanBackGestureEnable;
self.interactivePopGestureRecognizer.enabled = _isPanBackGestureEnable;
}
#pragma mark - UIGestureRecognizerDelegate
// 手势的代理方法
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
BOOL isShould = NO;
if ( (self.childViewControllers.count<=1) ) {
isShould = NO;
}else {
isShould = YES;
}
return isShould;
}
@end
2.在BaseViewController中当viewDidDisappear时禁用,viewDidAppear时根据情况禁用或开启
BaseViewController.h
#import "QqcBaseViewController.h"
@interface BaseViewController : QqcBaseViewController
#pragma mark - polymorphy
//是否需要滑动退场
- (BOOL)isPanBackGestureEnable;
@end
BaseViewController.m
#import "BaseViewController.h"
#import "QqcNavigationController.h"
@implementation BaseViewController
#pragma mark - polymorphy
//是否需要全屏滑动退场
- (BOOL)isPanBackGestureEnable {
return YES;
}
#pragma mark - system framework
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
//是否启用全屏滑动手势
BOOL isPanBackEnable = [self isPanBackGestureEnable];
((QqcNavigationController*)self.navigationController).isPanBackGestureEnable = isPanBackEnable;
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
//启用全屏滑动手势
((QqcNavigationController*)self.navigationController).isPanBackGestureEnable = NO;
}
@end
3.在SomeoneViewController中定制是否需要滑动返回手势
//是否需要滑动退场
- (BOOL)isPanBackGestureEnable {
return NO;
}