iOS中的导航栏UINavigationBar与工具栏UIToolBar要点解析

2020-01-15 15:34:47于丽

一、导航栏UINavigationBar
1、导航栏的使用

在iOS开发中,我们通常会使用导航控制器,导航控制器中封装了一个UINavigationBar,实际上,我们也可以在不使用导航控制器的前提下,单独使用导航栏,在UINavigationBar中,也有许多我们可以定制的属性,用起来十分方便。

2、UINavigationBar的创建和风格类型

导航栏继承于UIView,所以我们可以像创建普通视图那样创建导航栏,比如我们创建一个高度为80的导航栏,将其放在ViewController的头部,代码如下:

UINavigationBar *bar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 320, 80)];
[self.view addSubview:bar];

效果如下:

导航栏,UINavigationBar,工具栏,UIToolBar,iOS,UINavigation

我们也可以设置导航栏的风格属性,从iOS6之后,UINavigationBar默认为半透明的样式,从上面也可以看出,白色的导航栏下面透出些许背景的红色。导航栏的风格属性可以通过下面的属性来设置:

@property(nonatomic,assign) UIBarStyle barStyle;
UIBarStyle是一个枚举,其中大部分的样式都已弃用,有效果的只有如下两个:

typedef NS_ENUM(NSInteger, UIBarStyle) {
    UIBarStyleDefault          = 0,//默认
    UIBarStyleBlack            = 1,//黑色
}

默认的风格就是我们上面看到的白色的风格,黑色的风格效果瑞如下:

导航栏,UINavigationBar,工具栏,UIToolBar,iOS,UINavigation

3、导航栏常用属性和方法

从上面我们可以看到,iOS6后导航栏默认都是半透明的,我们可以通过下面的bool值来设置这个属性,设置为NO,则导航栏不透明,默认为YES:

@property(nonatomic,assign,getter=isTranslucent) BOOL translucent;
下面一些方法用于设置NavigationBar及上面item的颜色相关属性:

@property(null_resettable, nonatomic,strong) UIColor *tintColor;
tintColor这个属性会影响到导航栏上左侧pop按钮的图案颜色和字体颜色,系统默认是如下颜色:

导航栏,UINavigationBar,工具栏,UIToolBar,iOS,UINavigation

@property(nullable, nonatomic,strong) UIColor *barTintColor;
BarTintColor用于设置导航栏的背景色,这个属性被设置后,半透明的效果将失效: