0%

iOS实现右滑手势返回上一级

iOS实现右滑手势返回

1、申明实现代理

1
2
@interface BaseViewController ()<UIGestureRecognizerDelegate>

2、在viewDidLoad 方法中设置手势并禁用系统滑动手势

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
- (void)viewDidLoad {
[super viewDidLoad];
//1.获取系统interactivePopGestureRecognizer对象的target对象
id target = self.navigationController.interactivePopGestureRecognizer.delegate;

//2.创建滑动手势,taregt设置interactivePopGestureRecognizer的target,所以当界面滑动的时候就会自动调用target的action方法。
//handleNavigationTransition是私有类_UINavigationInteractiveTransition的方法,系统主要在这个方法里面实现动画的。
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] init];

[pan addTarget:target action:NSSelectorFromString(@"handleNavigationTransition:")];

//3.设置代理
pan.delegate = self;

//4.添加到导航控制器的视图上
[self.navigationController.view addGestureRecognizer:pan];

//5.禁用系统的滑动手势
self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

3、实现代理方法

1
2
3
4
5
6
7
8
9
10
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
//导航的rootViewController关闭右滑返回功能
if (self.navigationController.viewControllers.count <= 1)
{
return NO;
}
return YES;
}