[关闭]
@chenbinghua 2015-10-15T11:20:03.000000Z 字数 1840 阅读 2514

iOS开发之滑动返回失效

iOS笔记


当滑动返回失效时,有两种方法可以修复

方法一 (不推荐,只能在左侧滑动返回)

  1. 自定义UINavigationController.m文件
  2. 遵循UINavigationControllerDelegate协议
  3. - (void)viewDidLoad {
  4. [super viewDidLoad];
  5. // 还原滑动返回功能
  6. self.popDelegate = self.interactivePopGestureRecognizer.delegate;
  7. self.delegate = self;
  8. }
  9. - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
  10. {
  11. if (self.viewControllers.count != 0) { // 非根控制器
  12. viewController.hidesBottomBarWhenPushed = YES;
  13. // 设置导航条左边按钮的内容
  14. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"NavBack"] style:UIBarButtonItemStyleBordered target:self action:@selector(back)];
  15. // 就有滑动返回功能
  16. self.interactivePopGestureRecognizer.delegate = nil;
  17. }
  18. [super pushViewController:viewController animated:animated];
  19. }
  20. #pragma mark - UINavigationControllerDelegate
  21. - (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
  22. // 如果展示的是根控制器是根控制器,就还原pop手势代理
  23. if (viewController == [self.viewControllers firstObject]) {
  24. self.interactivePopGestureRecognizer.delegate = self.popDelegate;
  25. }
  26. }

方法二 (推荐,简单、全屏都能滑动返回)

  1. 自定义UINavigationController.m文件
  2. 遵循UIGestureRecognizerDelegate协议
  3. - (void)viewDidLoad {
  4. [super viewDidLoad];
  5. // 滑动返回相关
  6. [self slideToBack];
  7. }
  8. - (void)slideToBack{
  9. // 禁止系统原来的滑动返回手势,防止手势冲突
  10. self.interactivePopGestureRecognizer.enabled = NO;
  11. // 自定义滑动手势添加到self.view 调用系统原来的滑动返回方法
  12. // 即self.interactivePopGestureRecognizer.delegate的handleNavigationTransition:方法
  13. UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self.interactivePopGestureRecognizer.delegate action:@selector(handleNavigationTransition:)];
  14. pan.delegate = self;
  15. [self.view addGestureRecognizer:pan];
  16. }
  17. #pragma mark - 手势代理方法
  18. // 是否开始触发手势,如果是根控制器就不触发手势
  19. - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
  20. {
  21. // 判断下当前控制器是否是根控制器
  22. return (self.topViewController != [self.viewControllers firstObject]);
  23. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注