*.首先說明個普遍碰到的問題
網上普遍看到說, 在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下的返回滑動了, 和微信一樣一樣滴~~~~~