自定义NavigationController

继承于NavigationController创建XPFNavigationController
创建XPFNavigationController

.h
#import 

@interface XPFNavigationController : UINavigationController
@property (nonatomic, strong) UIImageView *navBarHairlineImageView;
- (void)back;

@end

.m
#import "XPFNavigationController.h"

@interface XPFNavigationController ()
{
    
}
@end

@implementation XPFNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    _navBarHairlineImageView = [self findHairlineImageViewUnder:self.navigationBar];
}
+ (void)initialize {
    UINavigationBar *bar = [UINavigationBar appearance];
    // 需求要求导航时图片
    //UIImage *bg = [UIImage imageNamed:@"navigationbarBackgroundWhite"];
    //[bar setBackgroundImage:bg forBarMetrics:UIBarMetricsDefault];
    // 设置导航文字颜色和大小
    [bar setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor]}];
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if (self.childViewControllers.count) {
        viewController.hidesBottomBarWhenPushed = YES;
        UIButton *button = [[UIButton alloc] init];
        [button setImage:[UIImage imageNamed:@"back_black"] forState:UIControlStateNormal];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        button.bounds = CGRectMake(0, 0, 30, 30);
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    }
    [super pushViewController:viewController animated:animated];
}


//2、找出底部横线的函数
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
- (void)back {
    [self popViewControllerAnimated:YES];
}



初始化导航添加Tabbar的时候

[self addChildViewController:[[XPFNavigationController alloc] initWithRootViewController:yourvc]];

首先隐藏导航下面的横线

_nav = [[XPFNavigationController alloc]init];
    _nav = (XPFNavigationController *)self.navigationController;
    _nav.navBarHairlineImageView.hidden = YES;

在- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated可以自定义返回按钮的图样
在initialize里设置导航的其他属性

你可能感兴趣的:(自定义NavigationController)