UINavigationController使用

来源:互联网 发布:淘宝交易指数是什么 编辑:程序博客网 时间:2024/05/18 06:20

UINavigationController在IOS项目中有广泛的应用,根据官方文档解释是:导航控制器管理一组视图控制器,以提供一个分层内容的钻取接口。也即是说,UINavigationController主要是用来包含其他控制器的栈;用于显示统一的导航栏,和不同控制器之间的导航。

如果不用UINavigationController我写导航栏是使用UINavigationBar,然后将UINavigationBar添加到控制器的view中,代码如下:

self.navigationBar=[[UINavigationBar alloc] init];self.navigationBar.barTintColor = UIColorFromRGB(nav_color);self.navigationBar.translucent = NO;self.navigationBar.backgroundColor=UIColorFromRGB(nav_color);[self.view addSubview:self.navigationBar];

如果使用UINavigationController整个过程就变得简单了:由IOS源码可知,每个UIViewController都包含一个UINavigationController,如果我们把根控制器设置成UINavigationController,那么UINavigationController就会统一管理控制器,代码如下:

LoginViewController *loginViewController=[[LoginViewController alloc] init];UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:loginViewController];navVC.navigationBarHidden = NO;self.window.rootViewController=navVC;
那么会给我们使用带来以下好处:

1.我们可以直接使用navVC.viewControllers获取到UINavigationController管理所有控制器。

2.不用为每个控制器加一个UINavigationBar,直接使用UINavigationController的就行

[self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName :[UIColor whiteColor],NSFontAttributeName:[UIFont fontWithName:@"Helvetica-Bold" size:nav_title_size] }];[self.navigationItem setTitle:@"登录界面"];
3.同时可以根据不同控制器里面不同的导航栏内容自己定义:

self.navigationItem.titleView=nil;self.navigationItem.title=@"登录";self.navigationItem.leftBarButtonItem=[self addLeftBtn];self.navigationItem.rightBarButtonItem=nil;


至于具体的使用可以参考:

https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewControllerCatalog/Chapters/NavigationControllers.html#//apple_ref/doc/uid/TP40011313-CH2-SW1




0 0