首页 > 代码库 > UINavigationController和UITabBarController

UINavigationController和UITabBarController

UINavigationController。展示上方的导航栏。UITabBarController,展示下方的tab栏。这2个组件都用得挺多

事实上另一个UIToolBar,能够单独使用,只是目測不太经常使用

container controller

UINavigationController和UITabBarController,都属于container controller。

用来容纳实际承载业务的ViewController

UIViewController *first = [[FirstViewController alloc] init];
UINavigationController *contactNav = [[UINavigationController alloc] initWithRootViewController:first];


然后是UITabBarController的使用方法:

UITabBarController *tab = [[UITabBarController alloc] init];
    
UIViewController *first = [[FirstViewController alloc] init];
UINavigationController *contactNav = [[UINavigationController alloc] initWithRootViewController:first];
    
UIViewController *second = [[SecondViewController alloc] init];
UINavigationController *reportNav = [[UINavigationController alloc] initWithRootViewController:second];
    
tab.viewControllers = @[contactNav, reportNav];

假设既须要导航栏,又要下方的tab栏,就能够用这种方法。先把实际的ViewController装到NavigationController里,再把NavigationController装到TabBarController里

控制导航栏和tab栏

控制导航栏和tab栏的button。不是由container controller自己做的,而是由实际的ViewController负责的,ios的这个设计比較灵活。能够实现同一个Navigation里的ViewController有各自独立的导航栏button。API也不复杂

UIBarButtonItem *logo = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"logo"] style:UIBarButtonItemStylePlain target:self action:@selector(logoPressed:)];
self.navigationItem.leftBarButtonItem = logo;
        
UIBarButtonItem *add = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:nil];
UIBarButtonItem *search = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:nil action:nil];
NSArray *rightButtons = [[NSArray alloc] initWithObjects:add, search, nil];
self.navigationItem.rightBarButtonItems = rightButtons;

self.title = @"通讯录首页";
        
self.tabBarItem.image = [UIImage imageNamed:@"logo"];
self.tabBarItem.title = @"通讯录";

通过ViewController自带的property navigationItem,就能够分别设置左边和右边的button了。假设ViewController没有包括在NavigationController里,这个属性貌似为nil。

title是在nav栏上显示的文字。tabBarItem是用来控制tab栏的显示,能够设置image和titile

UINavigationController和UITabBarController