您的位置:首页 > 移动开发 > IOS开发

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

2016-04-26 11:12 453 查看
方法非原创,来源资料查找和总结

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];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: