其他分享
首页 > 其他分享> > iOS 自定义返回按钮,保留系统滑动返回

iOS 自定义返回按钮,保留系统滑动返回

作者:互联网

 

 

 

1.简介

使用苹果手机,最喜欢的就是用它的滑动返回.作为一个开发者,我们在编写很多页面的时候,总是会因为这样那样的原因使得系统的滑动返回不可用.使用导航栏push出一个控制器,我们在控制器中自定义了一个返回按钮.这样系统默认的滑动返回手势效果就没有了.

2.解决方法

[1]从A这个控制器push到B这个控制器,我们想要自定义B的返回按钮,我们可以在A中设置

self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"王俨" style:UIBarButtonItemStylePlain target:nil action:nil];

[2]在B控制器设置返回按钮,我想这应该是大多数人喜欢的选择,可是当我们在B控制器中设置self.navigationItem.leftBarButtonItem后发现系统的滑动返回手势失效了.那么如何可以保留系统的滑动返回手势了,我们可以B控制器中这样做.

@interface ViewController () <UIGestureRecognizerDelegate>
@end

@implementation ViewController {
    id<UIGestureRecognizerDelegate> _delegate
}

- (void)viewDidLoad {
        [super viewDidLoad];
        
        // 自定义返回按钮
        UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
        [button setTitle:@"王俨2" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
        
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
}

- (void)back:(UIButton *)button {
        [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.navigationController.viewControllers.count > 1) {
          // 记录系统返回手势的代理
        _delegate = self.navigationController.interactivePopGestureRecognizer.delegate;
          // 设置系统返回手势的代理为当前控制器
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
     // 设置系统返回手势的代理为我们刚进入控制器的时候记录的系统的返回手势代理
    self.navigationController.interactivePopGestureRecognizer.delegate = _delegate;
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
        return self.navigationController.childViewControllers.count > 1;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return self.navigationController.viewControllers.count > 1;
}
@end

源地址

标签:返回,控制器,自定义,navigationController,iOS,button,self,delegate
来源: https://www.cnblogs.com/jiuyi/p/11544866.html