UINavigationController的视图层理关系

一.构成

(从底层往上数)

UINavigationController 的view

内容视图,也就是栈顶控制器的view

UINavigationBar:UIView

 

实例 : 

//设计nav的背景

[nav.view setBackgroundColor:[UIColor blueColor]]; 

 

//设置视图最上面的navigationBar

nav.navigationBar.barTintColor = [UIColor greenColor];//bartintcolor是ios7加进来的,在ios之前是使用tintcolor,在ios7之后被启用,虽然这个属性将不会有任何的效果

 

//设置内容视图的背景

[self.view setbackcolor:purpleColor]

 

效果如下: 

 

二.控制

nav.view 几乎是看不到的,无需控制

contentCon.view 所有的内容都是在这里设计的,也无需设置

 

我们这里需要详细理解的就是UINavigationBar与UINavigationItem的关系,这要我们就能够轻松自如的控制上面的导航条样式了.

 

且看UINavigationBar官方的介绍:

The UINavigationBar class provides a control for navigating hierarchical content…

navBar是用来管理导航栏内容层级关系的,由a left (back) button, a center title, and an optional right button组成,我们可以把它看做一个独立的对象或是跟navCon有者某张联系的对象

 

且看UINavigationItem官方的介绍:

A UINavigationItem object manages the buttons and views to be displayed in a UINavigationBar object

 

navItem是用来管理navBar上面元素的.是UI开头的,但是不要以为他是继承UI的,它是继承NSObject

这个管理navCon的对象会把视图最上面的item移动到内容视图的bar上面去

 

看了介绍我们可以得出总结:

UINavigationBar用在UINavgationController类中,用于管理和显示UINavgationController的subViewController , 同时UINavgationBar也可以单独使用,添加至任何的UIView中。

 

UINavigationItem就是用来管理,控制UINavgationBar上面的item的,UINavigationBar上面是用来装载item的.

 

理清楚了这些,再到相应的类中查看相应的方法就可以随心定制你自己导航栏了.

 

接下来我们将通过几个实例来玩玩我们刚刚理解的东西:

 

修改bar上面的title样式 

 

NSDictionary *titleAttr = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:18],NSFontAttributeName,[UIColor redColor],NSForegroundColorAttributeName, nil];

 

//利用navBar的TitleTextAttributes属性值来设置显示样式,里面的key在NSAttributedString.h文件当中

[nav.navigationBar setTitleTextAttributes:titleAttr]; 

 

现在我们实现一个需求,我们有时候present一个控制器,这个控制器一般都是没有导航栏的,如果我们项目整个都设置导航栏的样式,那么就会显得我们present出来的控制器与我们的项目格格不入,那么我们的需求就是:修改我们的present出来的con跟系统的一样

 

UIViewController *con = [[UIViewController alloc] init];

[con.view setBackgroundColor:[UIColor whiteColor]];

    

//con设置bar

UINavigationBar *bar = self.navigationController.navigationBar;

[con.view addSubview:bar];

[self.navigationController presentViewController:con animated:YES completion:nil];

 

这是把父类的传给下一个con,我们同时也是可以自定义navBar的,方法一样,这里不做累赘

 

2. 设置背景

(void)setBackgroundImage:(UIImage *)backgroundImage forBarMetrics:(UIBarMetrics)barMetrics 

 

3. 还可以通过navItem来修改navBar上面的btnItem,title,titleView内容

 

这样导航控制器想怎么搞就怎么搞了.

参考文献:http://my.oschina.net/hmj/blog/103332

原文地址:https://www.cnblogs.com/dlx-Blog/p/4414591.html