最近做了UINavigationController的滑动返回(IOS7及以后系统默认支持的), 主要分成以下几步以及碰到的问题, 我这里做个总结:
*.首先说明个普遍碰到的问题
网上普遍看到说, 在UINavigationController下自定义leftBarButtonItem会导致滑动失效, 解决方案:http://blog.csdn.net/meegomeego/article/details/25879605
但我想告诉大家, 我也是自定义了leftBarButtonItem却没有碰到上述问题, 我是统一写了一个BaseViewController作为所有controller父类, 除了rootConrtoller, 这里不知为何, 有知道的可以留言.
排除上述原因, 下面介绍下怎么实现滑动:
1. 自定义UINavigationController(我写了个UIBaseNavigationController)以共用, 在ViewDidLoad里加入代码:
- (void)viewDidLoad { [super viewDidLoad]; /* UINavigationControllerDelegate */ self.delegate = self; / swipe gesture / __weak typeof (self)weakSelf = self; if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) { // self.interactivePopGestureRecognizer.enabled = YES; /* UIGestureRecognizerDelegate */ self.interactivePopGestureRecognizer.delegate = weakSelf; } }
这里是将interactivePopGestureRecognizer.delegate赋给self. 这样便可以实现滑动, 因为enabled默认是YES.
2. 在滑动过程中你会发现如果在pushViewController的动画过程中激活滑动手势会导致crash, 解决方案:
/ set gesture no when pushViewController / - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated { if ([self respondsToSelector:@selector(interactivePopGestureRecognizer)]) { self.interactivePopGestureRecognizer.enabled = NO; } [super pushViewController:viewController animated:animated]; }
在push的时候关闭手势, 这样就不用担心会激活滑动
3. 自然, 在当你加载完成下一个viewController之后需要激活滑动手势:
/ set gesture yes when showViewController / - (void)navigationController:(UINavigationController )navigationController didShowViewController:(UIViewController )viewController animated:(BOOL)animated { if ([navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { navigationController.interactivePopGestureRecognizer.enabled = YES; } }
4. 当然, 你还会发现一个问题:在rootController下滑动的时候, 在想push到下一个页面会没有反应, 界面卡死在那了, 所以还需要在上述方法中加入以下代码:
/ set gesture yes when showViewController / - (void)navigationController:(UINavigationController )navigationController didShowViewController:(UIViewController )viewController animated:(BOOL)animated { if ([navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) { navigationController.interactivePopGestureRecognizer.enabled = YES; } / if rootViewController, set delegate nil / if (navigationController.viewControllers.count == 1) { navigationController.interactivePopGestureRecognizer.enabled = NO; navigationController.interactivePopGestureRecognizer.delegate = nil; } }
在判断当前为rootController, 设置手势无效, 而且必须设置delegate为nil, 这样的话就可以解决卡死的问题了.
这样的话, 就可以完成navigationcontroller下的返回滑动了, 和微信一样一样滴~~~~~
时间: 2024-10-11 07:39:35