iOS页面右滑返回的实现方法总结

1.边缘触发的系统方法

  ①系统返回按钮

   self.navigationController.interactivePopGestureRecognizer.enabled = YES;

 ②自定义返回按钮

 1. self.navigationController.interactivePopGestureRecognizer.enabled = YES;             2. self.navigationController.interactivePopGestureRecognizer.delegate = self;

在viewDidLoad里面加入这两行代码,遵循UIGestureRecognizerDelegate协议,当前的viewcontroller即可以实现该向右滑动后退功能,但是当回到navigationController的rootView中再次做出向右滑动时,程序会有问题(再次push子controller时,程序卡在当前界面无法跳转).有效解决方案如下:

说明:有两个controllerA,B

navigationController的rootview设置为A,在A中点击按钮后push B.在A的 -(void)viewDidAppear:(BOOL)animated方法中加入self.navigationController.interactivePopGestureRecognizer.enabled = NO;

2.全屏触发的自定义方法

2.1 自定义所有控制器的父类,在全屏范围内添加右滑手势,触发返回事件。

  在viewDidLoad中,创建UIPanGestureRecognizer,并添加到导航栏控制器上。

- (void) viewDidLoad {
    [super viewDidLoad];

    //1.获取系统interactivePopGestureRecognizer对象的target对象
    id target = self.navigationController.interactivePopGestureRecognizer.delegate;

    //2.创建滑动手势,taregt设置interactivePopGestureRecognizer的target,所以当界面滑动的时候就会自动调用target的action方法。
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] init];
    [pan addTarget:target action:NSSelectorFromString(@"handleNavigationTransition:")];
    pan.delegate = self;

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

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

在滑动开始的触发事件中控制除了根视图控制器以外的所有控制器执行右滑事件。

#pragma mark - 滑动开始触发事件
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    //只有导航的根控制器不需要右滑的返回的功能。
    if (self.navigationController.viewControllers.count <= 1) {
        return NO;
    }

    return YES;
}

这种实现方法在一定程度上解决了问题,但有局限性。一是其触发是在所有次级控制器上作用,若部分控制器不需要该功能无法取消手势;二是在实际应用中可能导致手势冲突或因手指右滑停止而再返回原页面而引起错误或崩溃。

2.2 从底层入手,创建一个UINavigationController的分类(category),从根本上解决右滑返回的问题。

这一成果来自Github上forkingdog的开源项目,使用方法很简单,只需在你的项目中导入UINavigationController+FDFullscreenPopGesture这一分类,编译通过后即可实现全屏幕的右滑返回,若需在某一个页面取消事件,只需要引入UINavigationController+FDFullscreenPopGesture.h文件,然后在viewDidLoad方法中设置self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO,并在上一个页面的viewWillAppear方法中设置self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES,就可自如地控制各个页面的右滑返回效果实现与否。这一方法稳定而简便地解决了问题。
原文地址:https://www.cnblogs.com/Mr-zyh/p/7451608.html