UINaviGationController通常被我们称为导航栏,他是视图与视图之间联系沟通的桥梁,一些著名的app都用到了他。下面我们来看一下如何建立一个navigation。
首先,我们通常新建工程是直接将视图控制器添加到window上,而现在有navigation以后,就多了一层:
Appdelegete.h:
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
- // Override point for customization after application launch.
- self.window.backgroundColor = [UIColor whiteColor];
- RootViewController *root = [[RootViewController alloc]init];
- UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:root];//先将root添加在navigation上
- [_window setRootViewController:nav];//navigation加在window上
- [nav release];
- [root release];
- [self.window makeKeyAndVisible];
- return YES;
- }
这样我们的navigation就加载上去了。下面我们来设置navigation的属性:
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view.
- [self.navigationController.navigationBar setTranslucent:NO];//设置navigationbar的半透明
- self.title = @"navigationcontroller";//设置navigationbar上显示的标题
- [self.navigationController.navigationBar setBarTintColor:[UIColor purpleColor]];//设置navigationbar的颜色
- self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonItemStyleDone target:self action:Nil];//设置navigationbar左边按钮
- self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonItemStylePlain target:self action:Nil];//设置navigationbar右边按钮
- [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];//设置navigationbar上左右按钮字体颜色
- }
这里还有一个属性常用,就是:
- NSArray *arr = [NSArray arrayWithObjects:@"1",@"2", nil nil];
- UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:arr];
- self.navigationItem.titleView = segment;//设置navigation上的titleview
中间的字变成了两个可选的按钮,这就是navigation的另一个属性:navigationitem.titleview。
我们再建立一个视图,看一下两个视图之前是怎样通信的。
在第二个视图中,我添加了一个button来显示,并加了一个成员变量来接收从第一个视图中穿过来的值:
- @interface SecondViewController : UIViewController
- @property (copy,nonatomic) NSString *str;
- @end
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view.
- self.title = @"second";
- UIButton *aBUTTON = [[UIButton alloc]initWithFrame:CGRectMake(30, 30, 50, 30)];
- [aBUTTON setTitle:_str forState:UIControlStateNormal];
- [aBUTTON addTarget:self action:@selector(clicked) forControlEvents:UIControlEventTouchUpInside];
- [self.view addSubview:aBUTTON];
- }
然后我将第一个视图的右边按钮添加一个事件,点击按钮,就会推出第二个视图,并显示我们传过来的值:
- - (void)clicked{
- SecondViewController *second = [[SecondViewController alloc]init];
- [self.navigationController pushViewController:second animated:YES];
- second.str = @"hello!!";
- [second release];
- }
点进按钮以后,我们的第二个视图推出,button显示了传过来的值。
然后我们点击回button,还有navigation另外一个方法:
- - (void)clicked{
- [self.navigationController popViewControllerAnimated:YES];
- }
这样就可以回到第一个视图。