UINaviGationController通常被我們稱為導航欄,他是視圖與視圖之間聯系溝通的橋梁,一些著名的app都用到了他。下面我們來看一下如何建立一個navigation。
首先,我們通常新建工程是直接將視圖控制器添加到window上,而現在有navigation以后,就多了一層:
Appdelegete.h:
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
- {
- self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
-
- self.window.backgroundColor = [UIColor whiteColor];
- RootViewController *root = [[RootViewController alloc]init];
- UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:root];
- [_window setRootViewController:nav];
-
- [nav release];
- [root release];
-
- [self.window makeKeyAndVisible];
- return YES;
- }
這樣我們的navigation就加載上去了。下面我們來設置navigation的屬性:
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
- [self.navigationController.navigationBar setTranslucent:NO];
- self.title = @"navigationcontroller";
- [self.navigationController.navigationBar setBarTintColor:[UIColor purpleColor]];
- self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonItemStyleDone target:self action:Nil];
- self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonItemStylePlain target:self action:Nil];
- [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
- }
效果圖如下:

這里還有一個屬性常用,就是:
- NSArray *arr = [NSArray arrayWithObjects:@"1",@"2", nil nil];
- UISegmentedControl *segment = [[UISegmentedControl alloc]initWithItems:arr];
- self.navigationItem.titleView = segment;
效果如下:

對,我們看到中間的字變成了兩個可選的按鈕,這就是navigation的另一個屬性:navigationitem.titleview。
下面我們再建立一個視圖,看一下兩個視圖之前是怎樣通信的。
在第二個視圖中,我添加了一個button來顯示,并加了一個成員變量來接收從第一個視圖中穿過來的值:
- @interface SecondViewController : UIViewController
- @PRoperty (copy,nonatomic) NSString *str;
- @end
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
- 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];
- }
這樣就可以回到第一個視圖。
uinavigationcontroller的一些簡單的屬性就先說到這里,歡迎留言補充,謝謝。