iOS系统支持边缘右滑返回,但这样的前提是用的是系统的navigationItem的backBarButtonItem。
但是很多情况下我们的navigationItem都是自定义的,这样就回失去右滑返回的效果。建议大家如果有需要自定义的nav,最好整个app内统一都用自定义的nav bar来写,不然添加右滑返回后,可能会出现导航条错乱的问题
方法一:在baseController的viewDidLoad里写如下代码
self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
但是我试了这样的方法,可能引起程序卡死甚至崩溃。查了网上很多方法,都试了但是也没有解决我的问题,所以我没有采用这个方法
方法二:在baseController的viewDidLoad里添加
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(back:)];
swipe.delegate = self;
[self.view addGestureRecognizer:swipe];
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
然后实现back方法
- (void)back:(UISwipeGestureRecognizer*)swipe {
if (self.navigationController.viewControllers.count <= 1) return;
[self.navigationController popViewControllerAnimated:YES];
}
方法二的弊端也很明显,不能看到右滑的中间态,只要触发右滑手势就回返回到上一级目录
方法三:在baseController的viewDidLoad添加
id target = self.navigationController.interactivePopGestureRecognizer.delegate;
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:target action:@selector(handleNavigationTransition:)];
pan.delegate = self;
[self.view addGestureRecognizer:pan];
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
这样后发现不光是向右滑动,连向左滑动也会返回,不要着急,再加我下边的这个方法就搞定啦。
- (BOOL)gestureRecognizerShouldBegin:(UIPanGestureRecognizer *)gestureRecognizer {
CGPoint point = [gestureRecognizer translationInView:self.view];
if (point.x > 0) {
return YES;
} else {
return NO;
}
}
搞定了,可以试试哦,有什么问题可以直接留言,我们一起讨论哦