iOS学习笔记-OC-(1)自定义返回手势

学习目的:
*解决重写navigationItem.leftBarButtonItem导致系统自动右滑返回手势失效.

实现效果:
在push后的控制器中,通过右滑手势返回上一个控制器,不仅仅在屏幕边缘能实现返回(在屏幕中间右滑也能返回).

1.在自定义的导航控制器viewDidLoad方法中实现:

- (void)viewDidLoad {

[super viewDidLoad];

UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self.interactivePopGestureRecognizer.delegate action:@selector(handleNavigationTransition:)];

[self.view addGestureRecognizer:pan];

// 控制手势什么时候触发,只有非根控制器才需要触发手势

pan.delegate = self;

// 禁止之前手势

self.interactivePopGestureRecognizer.enabled = NO;

}

2.解决返回到根控制器界面,再继续右滑导致卡死的Bug:
2.1.遵守UIGestureRecognizerDelegate协议

@interface FitfunNavigationController ()

2.2.实现代理协议方法

#pragma mark - UIGestureRecognizerDelegate
// 决定是否触发手势
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    return self.childViewControllers.count > 1;
}

3.重写UINavigationController的方法(- pushViewController: animated:):

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (self.childViewControllers.count > 0) { // 非根控制器
        viewController.hidesBottomBarWhenPushed = YES;
     
        // 设置返回按钮,只有非根控制器
        viewController.navigationItem.leftBarButtonItem = [UIBarButtonItem fitfun_backItemWithimage:[UIImage imageNamed:@"navigationButtonReturn"] highImage:[UIImage imageNamed:@"navigationButtonReturnClick"]  target:self action:@selector(back) title:@"返回"];
    }
    
    // 真正在跳转
    [super pushViewController:viewController animated:animated];
}

- (void)back
{
    [self popViewControllerAnimated:YES];
}

你可能感兴趣的:(iOS学习笔记-OC-(1)自定义返回手势)