標籤:
xcode:6.3.2
ios8.3
介紹:在平時項目開發中,UINavigationController的使用非常廣泛,很多優秀的APP都採用了導覽列,導覽列對於視圖控制方面非常便捷。
先來看一張官方的圖
1,建立項目Nav
2,添加FirstViewController用於根視圖,添加SecondViewController用於根視圖跳轉到的視圖
3,在AppDelegate.m檔案中,修改代理,使得FirstViewController為根視圖,如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { FirstViewController *first = [[FirstViewController alloc] init]; UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:first]; [self.window setRootViewController:nav]; [self.window makeKeyAndVisible]; return YES;}
4,在FirstViewController.m中設定navigationController的相關屬性,如下:
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor redColor]; self.title = @"首頁"; //設定標題 [self.navigationController.navigationBar setBarTintColor:[UIColor purpleColor]];//設定navigationbar的顏色 [self.navigationController.navigationBar setTranslucent:YES];//設定navigationbar的半透明 self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(cameraStart)];//設定navigationbar左邊按鈕 self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(toSecond)];//設定navigationbar右邊按鈕 }
樣式:
5,實現toSecond方法push到SecondViewController
- (void)toSecond { SecondViewController *second = [[SecondViewController alloc] init]; [self.navigationController pushViewController:second animated:YES];}
6,在SecondViewController.m中添加按鈕,用於pop回FirstViewController,代碼如下
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor blueColor]; UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 200, 40)]; [button setTitle:@"返回" forState:UIControlStateNormal]; button.backgroundColor = [UIColor blackColor]; [button addTarget:self action:@selector(backToFirstViewController) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; // [self.navigationController.navigationBar setHidden:YES];}- (void)backToFirstViewController { [self.navigationController popViewControllerAnimated:YES]; // [self.navigationController.navigationBar setHidden:NO];}
樣式如下:
7,隱藏navigationBar,開啟注釋,設定navigationBar隱藏,同時在返回FirstViewController的方法中讓navigationBar顯示回來
[self.navigationController.navigationBar setHidden:YES];
源碼地址:https://github.com/rokistar/UsingUINavigationController
iOS導覽列使用