首页 > 代码库 > 自定义UINavigationController(导航控制器)

自定义UINavigationController(导航控制器)

首先,我先说说怎样自定义导航控制器。

1.自定义导航控制器需要新建一个类继承UINavigationController。如图:


2.在initialize方法中,自定义一些属于自己的navigationBar的一些东西。比如:颜色,文字,适配IOS7等等...

/**
 *  初始化(每一个类只会调用一次)
 */
+ (void)initialize
{
    [UIColor colorWithRed:226/255.0 green:226/255.0 blue:226/255.0 alpha:1.0];
    
    // 1.获得bar对象
    UINavigationBar *navBar = [UINavigationBar appearance];
    
    // 2.不是iOS7
    if (!iOS7) {
        // 2.1.设置bar背景
        [navBar setBackgroundImage:[UIImage imageWithName:@"navigationbar_background"] forBarMetrics:UIBarMetricsDefault];
        
        // 2.2.设置状态栏为黑色
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
    }
    
    // 3.设置文字样式
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[UITextAttributeTextColor] = [UIColor blackColor];
    attrs[UITextAttributeTextShadowOffset] = [NSValue valueWithUIOffset:UIOffsetMake(0, 0)];
    attrs[UITextAttributeFont] = iOS7 ? [UIFont systemFontOfSize:20]: [UIFont boldSystemFontOfSize:20];
    [navBar setTitleTextAttributes:attrs];
    
    // 4.设置导航栏按钮的主题
    UIBarButtonItem *barItem = [UIBarButtonItem appearance];
    
    // 5.设置按钮的背景
    if (!iOS7) {
        [barItem setBackgroundImage:[UIImage imageWithName:@"navigationbar_button_background"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
        [barItem setBackgroundImage:[UIImage imageWithName:@"navigationbar_button_background_pushed"] forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
        [barItem setBackgroundImage:[UIImage imageWithName:@"navigationbar_button_background_disable"] forState:UIControlStateDisabled barMetrics:UIBarMetricsDefault];
    }
    
    // 6.设置按钮的文字样式
    NSMutableDictionary *itemAttrs = [NSMutableDictionary dictionary];
    itemAttrs[UITextAttributeTextColor] = iOS7 ? [UIColor orangeColor] : [UIColor blackColor];
    itemAttrs[UITextAttributeTextShadowOffset] = [NSValue valueWithUIOffset:UIOffsetMake(0, 0)];
    [barItem setTitleTextAttributes:itemAttrs forState:UIControlStateNormal];
    [barItem setTitleTextAttributes:itemAttrs forState:UIControlStateHighlighted];
}