现在默认的iOS app都支持手势滑动返回功能 ,但是如果自定义了导航栏之后 手势滑动返回功能就会失效
怎样才能在自定义了导航栏之后手势滑动返回功能还能使用呢?可以这样设置
在NavigationController的viewDidLoad函数中添加如下代码
- (void)viewDidLoad {
[super viewDidLoad];
__weak IBNavigationController *weakSelf = self;
if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.delegate = weakSelf;
self.interactivePopGestureRecognizer.delegate = weakSelf;
}
}
这样写了以后就可以通过手势滑动返回上一层了,但是如果在push过程中触发手势滑动返回,会导致导航栏崩溃(从日志中可以看出)。针对这个问题,我们需要在pop过程禁用手势滑动返回功能:
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.interactivePopGestureRecognizer.enabled = NO;
}
[super pushViewController:viewController animated:animated];
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if ([navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
navigationController.interactivePopGestureRecognizer.enabled = YES;
if (navigationController.viewControllers.count == 1) {
navigationController.interactivePopGestureRecognizer.enabled = NO;
navigationController.interactivePopGestureRecognizer.delegate = nil;
}
}
}
这样就可以实现自定义导航栏 而且手势滑动返回功能不会失效