UINavigationBar 使用总结

 

UINavigationBar是咱们在开发过程当中常常要用到的一个控件,下面我会为你们介绍一些经常使用的用法。html

1. 设置导航栏的标题

这个很少说,直接上代码
self.navigationItem.title = @"UINavigationBar使用总结";ios

2. 设置导航栏的背景颜色

//经过barTintColor来设置背景色
 self.navigationController.navigationBar.barTintColor = [UIColor redColor];

获得的效果以下:git

Snip20150912_1.pnggithub

barTintColor: 这个属性须要在iOS7以上才可使用; 若是要支持iOS6以及如下的系统,能够参考这篇文章:UINavigationBar Background Color 微信

3. 设置导航栏的背景图片

除了经过设置背景颜色来改变导航栏的外观外,咱们还能够经过背景图片来设置导航栏的外观。app

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Background"]
                                                  forBarMetrics:UIBarMetricsDefault];

Snip20150912_2.pngide

在这里得稍微说说UIBarMetrics这个枚举, 它主要是用来控制在不一样状态下导航栏的显示。和UIButton的
- (void)setBackgroundImage:(nullable UIImage *)image forState:(UIControlState)state这个方法有点相似。字体

//表示横屏竖屏都显示
UIBarMetricsDefault,
//表示在只横屏下才显示,和UIBarMetricsLandscapePhone功效同样,不过iOS8已经弃用了
UIBarMetricsCompact,
UIBarMetricsDefaultPrompt和UIBarMetricsCompactPrompt这两个我还没搞清楚是什么意思,有知道的朋友不妨给咱们来普及一下。。ui

4. 更改顶部状态栏的颜色

从效果图能够看出,咱们设置背景色或者背景图以后,状态栏依然仍是默认的黑色,这样感受很差看。好在,系统给咱们提供了UIStatusBarStyleDefaultUIStatusBarStyleLightContent两种样式供咱们选择。spa

  • UIStatusBarStyleDefault,系统的默认样式,黑色内容,用于浅色的背景(如白色)
  • UIStatusBarStyleLightContent 白色内容,用于深色的背景(如红色)

下面来看看具体怎么实现,主流的实现方式是分两步:

  1. 在工程的Info.plist文件中添加一行UIViewControllerBasedStatusBarAppearance,选择Boolean类型,并设置为YES,Xcode会自动把名称变为View controller-based status bar appearance。

    Snip20150913_4.png

  2. 在你的ViewController中添加下面的方法
    -(UIStatusBarStyle)preferredStatusBarStyle{
     return UIStatusBarStyleLightContent;
    }

想知道更多地方式,能够参考这两个页面:How to change Status Bar text color in iOS 7 和 iOS7下Status Bar字体颜色修改

另外,特别须要注意的是,若是你的ViewController是经过navigationController push进来的,还须要加下面一句代码才能生效:
self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
具体,可参考UIStatusBarStyle PreferredStatusBarStyle does not work on iOS 7

恩,咱们来看看运行效果。

Snip20150913_5.png

5. 设置返回按钮

从上面的效果图中咱们能够看到返回按钮仍是默认的蓝色按钮,下面我将会你们来介绍返回按钮的个性化。

  • 设置返回按钮的颜色
    只须要设置tintColor属性便可
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    获得的效果图以下:

    Snip20150915_1.png

  • 只设置返回按钮的图片
- (void)goToBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setBackButtonWithImage {
    UIImage *leftButtonIcon = [[UIImage imageNamed:@"LeftButton_back_Icon"]
                               imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:leftButtonIcon
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:self
                                                                  action:@selector(goToBack)];
    self.navigationItem.leftBarButtonItem = leftButton;

    //修复navigationController侧滑关闭失效的问题
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}

获得的效果以下:

Snip20150915_2.png

这里须要注意的地方有三点:

  1. 须要本身实现返回按钮的事件。
  2. 特别的解释下UIImage的imageWithRenderingMode:方法,参数UIImageRenderingModeAlwaysOriginal 表示老是用原图渲染,若是不这么设置,返回按钮将会显示tintColor的颜色(默认为蓝色)。UITabbarItem也存在一样地问题。 
  3. 咱们本身设置返回按钮,会致使系统的侧滑关闭效果失效。添加上面代码中最后一句代码便可修复。
  • 仅设置返回按钮的文字
- (void)setBackButtonTitle {
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"取消", nil)
                                                                   style:UIBarButtonItemStylePlain
                                                                  target:self action:@selector(goToBack)];
    leftButton.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = leftButton;
}

获得的效果以下:

Snip20150915_3.png

  • 自定义返回按钮
    若是上面几种方式还没法知足你的要求(好比,须要同时设置返回按钮文字和图片),就须要用到UIBarButtonIteminitWithCustomView方法。
- (void)setCustomLeftButton {
    UIView* leftButtonView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 60, 40)];
    UIButton* leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftButton.backgroundColor = [UIColor clearColor];
    leftButton.frame = leftButtonView.frame;
    [leftButton setImage:[UIImage imageNamed:@"LeftButton_back_Icon"] forState:UIControlStateNormal];
    [leftButton setTitle:@"返回" forState:UIControlStateNormal];
    leftButton.tintColor = [UIColor redColor];
    leftButton.autoresizesSubviews = YES;
    leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    leftButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
    [leftButton addTarget:self action:@selector(goToBack) forControlEvents:UIControlEventTouchUpInside];
    [leftButtonView addSubview:leftButton];
    UIBarButtonItem* leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:leftButtonView];
    self.navigationItem.leftBarButtonItem = leftBarButton;
}

获得的效果图以下:

Snip20150915_5.png

设置rightBarButtonItem基本上脱离不了上面的几种方式,你们能够参照上面返回按钮的设置方式。

6. 隐藏导航栏底部的线条

有时候遇到一些特殊的要求,须要隐藏导航栏底部的线条。
两行代码就能够作到。

  • 设置导航栏的背景图(setBackgroundImage方法)
  • 设置导航栏的shadowImage (setShadowImage方法)
UINavigationBar *navigationBar = self.navigationController.navigationBar;
    //设置透明的背景图,便于识别底部线条有没有被隐藏
    [navigationBar setBackgroundImage:[[UIImage alloc] init]
                       forBarPosition:UIBarPositionAny
                           barMetrics:UIBarMetricsDefault];
    //此处使底部线条失效
    [navigationBar setShadowImage:[UIImage new]];

来看看效果图:

Snip20150922_1.png

另外,还有一种作法,一行代码就能够达到效果,也真是够神奇的。。

//方法二:
    self.navigationController.navigationBar.clipsToBounds = YES;

想要知道更详细的内容能够参考这个页面:How to hide iOS7 UINavigationBar 1px bottom line

7. 设置导航条底部线条的颜色

有了上面的基础,设置导航栏线条的颜色就变得很简单了。
首先,我作了个UIImage的分类:经过颜色转成UIImage;
而后,用上面的方案来设置导航栏底部线条。

颜色转图片的代码:

@implementation UIImage (ColorImage)

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

@end

设置导航栏底部线条颜色的代码:

UINavigationBar *navigationBar = self.navigationController.navigationBar;
    [navigationBar setBackgroundImage:[[UIImage alloc] init]
                       forBarPosition:UIBarPositionAny
                           barMetrics:UIBarMetricsDefault];
    //此处使底部线条颜色为红色
    [navigationBar setShadowImage:[UIImage imageWithColor:[UIColor redColor]]];

依照惯例,看下效果图:

Snip20150923_2.png

固然还有其余的方式也能够作到,如addSubview, addSubLayer等。感兴趣的话能够参考下这个页面:iOS7 - Change UINavigationBar border color

8. 在导航栏上添加多个按钮

以微信打开网页时的效果为例,效果图以下,有两个按钮:返回和关闭。

微信效果图.png


有下面两种方式可供选择,可是最终仍是要用到leftBarButtonItems这个方法。

#define UserMethod1 0

    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeAction)];
    if (UserMethod1) {
        //方法一:
        self.navigationItem.leftBarButtonItems = @[closeItem];
        //要求显示默认的返回按钮,可是文字会显示默认的Back,暂时还不知道这个文字怎么改
        self.navigationItem.leftItemsSupplementBackButton = YES;
    }
    else {
        //方法二
        UIButton* leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
        leftButton.backgroundColor = [UIColor clearColor];
        leftButton.frame = CGRectMake(0, 0, 45, 40);
        [leftButton setImage:[UIImage imageNamed:@"LeftButton_back_Icon"] forState:UIControlStateNormal];
        [leftButton setTitle:@"返回" forState:UIControlStateNormal];
        leftButton.tintColor = [UIColor whiteColor];
        leftButton.autoresizesSubviews = YES;
        leftButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        leftButton.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin;
        [leftButton addTarget:self action:@selector(goToBack) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem* backItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];

        self.navigationItem.leftBarButtonItems = @[backItem,closeItem];
    }

而后,运行的效果图以下:

在导航栏上添加多个按钮.png

方法一用到了leftItemsSupplementBackButton 这个属性,会显示系统默认的返回按钮,可是文字也是显示默认的Back文字,目前还没找到怎么修改这个文字,若是有谁知道,还请不吝赐教;因此我暂时仍是建议你们用方法二。相应的还有 rightBarButtonItems这个属性,若是要在导航栏右侧展现多个按钮的话,能够设置这个属性。

9. 在导航栏上添加分段控件

此次,以QQ为例,代码以下:

UISegmentedControl *segControl = [[UISegmentedControl alloc] initWithItems:@[@"消息",@"电话"]];
    segControl.tintColor = [UIColor colorWithRed:0.07 green:0.72 blue:0.96 alpha:1];
    [segControl setSelectedSegmentIndex:0];
    self.navigationItem.titleView = segControl;

代码很简单,就是设置titleView这个属性,固然,你也能够把这个属性设置为你自定义的View。

相似于QQ的导航栏.png

10. 导航栏全局属性设置

//全局设置导航栏主题
- (void)setNavigationControllerAppearance {
    [UINavigationBar appearance].barStyle  = UIBarStyleBlack;
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithWhite:0.1 alpha:0.5]];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
}

全局设置导航栏的好处有两个:一是不用对每一个NavigationBar进行设置;二是方便作主题管理,切换主题,只须要更改全局设置便可。

11. 与导航栏相关的一些开源组件

11.1 NJKWebViewProgress - 相似于Safiri加载网页时的进度显示

网页加载进度.png

11.2 FDFullscreenPopGesture - 一个丝滑的全屏滑动返回手势

对应的文章介绍能够点这个连接

丝滑的全屏返回手势.png

最后,奉上Demo的地址:NavigationBarDemo

相关文章
相关标签/搜索