iOS修改导航返回按钮内容和返回指定页

方法非原创,来源资料查找和总结

1.修改导航返回按钮文字:

在push之前添加要返回按钮显示的内容:

UIBarButtonItem *returnButton = [[UIBarButtonItem alloc] init];
    
returnButton.title = @"返回";
    
self.navigationItem.backBarButtonItem = returnButton;


2.要控制返回按钮指定页,需要拿到点击返回按钮的点击事件,在此增加两个类别1.UIViewController+BackButtonHandler 2.UINavigationController+ShouldPopOnBackButton

在UIViewController+BackButtonHandler.h文件中:


@protocol BackButtonHandlerProtocol <NSObject>

@optional
-(BOOL)navigationShouldPopOnBackButton;

@end
#import <UIKit/UIKit.h>

@interface UIViewController (BackButtonHandler)<BackButtonHandlerProtocol>

@end


在UIViewController+BackButtonHandler.m中不用做处理

#import "UIViewController+BackButtonHandler.h"

@implementation UIViewController (BackButtonHandler)

@end


在UINavigationController+ShouldPopOnBackButton.m文件中

#import "UINavigationController+ShouldPopOnBackButton.h"
#import "UIViewController+BackButtonHandler.h"

@implementation UINavigationController (ShouldPopOnBackButton)

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem*)item {
    
    if([self.viewControllers count] < [navigationBar.items count]) {
        return YES;
    }
    
    BOOL shouldPop = YES;
    UIViewController* vc = [self topViewController];
    if([vc respondsToSelector:@selector(navigationShouldPopOnBackButton)]) {
        shouldPop = [vc navigationShouldPopOnBackButton];
    }
    
    if(shouldPop) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self popViewControllerAnimated:YES];
        });
    } else {
        for(UIView *subview in [navigationBar subviews]) {
            if(subview.alpha < 1.) {
                [UIView animateWithDuration:.25 animations:^{
                    subview.alpha = 1.;
                }];
            }
        }
    }
    
    return NO;
}

@end

至此只要在你需要控制返回按钮的页面添加一下方法就可以获取返回按钮的点击事件

-(BOOL) navigationShouldPopOnBackButton //在这个方法里写返回按钮的事件处理
{
    //这里写要处理的代码****
    return NO;//返回NO 不会执行
}

****

处理的代码可以根据需要自己编写,以下是控制返回指定页的代码

修改导航返回指定页
当push层级有多层时,要返回到其中某个页面:
确定需要返回的页面是层级中的第几个,然后根据指定页pop
UIViewController *Xview = self.navigationController.viewControllers[1];//取数组中第几个页面
[self.navigationController popToViewController:Xview animated:YES];

当要返回根视图时
[self.navigationController popToRootViewControllerAnimated:YES];


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值