一、顯示Toolbar git
在RootViewController.m的- (void)viewDidLoad方法中添加代碼,這樣Toobar就顯示出來了。github
- [self.navigationController setToolbarHidden:NO animated:YES];
二、在ToolBar上添加UIBarButtonItem數組
新建幾個UIBarButtonItem,而後以數組的形式添加到Toolbar中flex
- UIBarButtonItem *one = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:nil action:nil];
- UIBarButtonItem *two = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:nil action:nil];
- UIBarButtonItem *three = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:nil action:nil];
- UIBarButtonItem *four = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:nil action:nil];
- UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
- [self setToolbarItems:[NSArray arrayWithObjects:flexItem, one, flexItem, two, flexItem, three, flexItem, four, flexItem, nil]];
效果:
![](http://static.javashuo.com/static/loading.gif)
注意:用 [self.navigationController.toolbar setItems:(NSArray *) animated:<#(BOOL)#>]這個方法添加item是不起效果的。下面我動態本身添加Toolbar時,這個才起效果。spa
三、動態添加Toolbar.net
咱們在SecondView添加動態的Toolbar。blog
在SecondViewController.h添加three
- #import <UIKit/UIKit.h>
-
- @interface SecondViewController : UIViewController
- {
- UIToolbar *toolBar;
- }
- @end
在SecondViewController.m添加
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
- [self.navigationController setToolbarHidden:YES animated:YES];
-
- UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(gotoThridView:)];
- toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0, self.view.frame.size.height - toolBar.frame.size.height - 44.0, self.view.frame.size.width, 44.0)];
- [toolBar setBarStyle:UIBarStyleDefault];
- toolBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
- [toolBar setItems:[NSArray arrayWithObject:addButton]];
- [self.view addSubview:toolBar];
-
- // Do any additional setup after loading the view from its nib.
- }
先把RootView時顯示的Toobar隱藏
[self.navigationController setToolbarHidden:YESanimated:YES];而後把新建的Toolbar添加的SecondView中,併爲Toobar設置了一個Item. get
[toolBarsetItems:[NSArrayarrayWithObject:addButton]]; it
BarButtonItem用 的是UIBarButtonSystemItemSearch, 效果以下:
![](http://static.javashuo.com/static/loading.gif)
四、新建ThridView,從SecondView跳轉到
Commad+N新建一個ThridViewController,
這個addButton跳轉到ThridView
- -(void)gotoThridView:(id)sender
- {
- ThridViewController *thridView = [[ThridViewController alloc] init];
- [self.navigationController pushViewController:thridView animated:YES];
- thridView.title = @"Thrid View";
-
- }
跳轉Second到Third效果:
![](http://static.javashuo.com/static/loading.gif)
到此UINavigationController練習的差很少了。
例子代碼:https://github.com/schelling/YcDemo