1. 程式人生 > >UINavigationController和UITabBarController

UINavigationController和UITabBarController

lai 使用 arc view nsa containe items 單獨使用 with

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