微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

源地址

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐