一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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

时间:2022-06-25 23:30:59 编辑:袖梨 来源:一聚教程网

先给大家展示下效果图:

1679203-9008e5fab32df21b.gif

 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控制器中这样做.

 

 代码如下复制代码

@interfaceViewController () 

@end@implementationViewController

- (void)viewDidLoad {

    [superviewDidLoad];   // 自定义返回按钮

    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 {

  [superviewWillAppear:animated]; if(self.navigationController.viewControllers.count >1) {    // 记录系统返回手势的代理

    _delegate = self.navigationController.interactivePopGestureRecognizer.delegate;    // 设置系统返回手势的代理为当前控制器

    self.navigationController.interactivePopGestureRecognizer.delegate = self;

  }

}

- (void)viewWillDisappear:(BOOL)animated {

  [superviewWillDisappear:animated];  // 设置系统返回手势的代理为我们刚进入控制器的时候记录的系统的返回手势代理

  self.navigationController.interactivePopGestureRecognizer.delegate = _delegate;

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

}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { returnself.navigationController.viewControllers.count >1;

}@end

 

热门栏目