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栏的按钮,不是由container controller自己做的,而是由实际的ViewController负责的,ios的这个设计比较灵活,可以实现同一个Navigation里的ViewController有各自独立的导航栏按钮,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,就可以分别设置左边和右边的按钮了。如果ViewController没有包含在NavigationController里,这个属性貌似为nil。title是在nav栏上显示的文字。tabBarItem是用来控制tab栏的显示,可以设置image和titile

你可能感兴趣的:(UINavigationController和UITabBarController)