IOS NavigationController Toolbar学习笔记
1、首先将toolbar显示出来,在viewDidLoad中添加代码让toolbar显示,代码如下:
- [self.navigationController setToolbarHidden:NO animated:YES]
显示如下图:
2、在ToolBar上添加UIBarButtonItem
新建几个UIBarButtonItem,然后以数组的形式添加到Toolbar中
- UIBarButtonItem *camera=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(ClickToolBarButton)];
- [camera setWidth:80];
- UIBarButtonItem *refresh=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(ClickToolBarButton)];
- [refresh setWidth:80];
- UIBarButtonItem *reply=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(ClickToolBarButton)];
- [reply setWidth:80];
- UIBarButtonItem *compose=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(ClickToolBarButton)];
- [compose setWidth:80];
- UIBarButtonItem *splitspace=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
- [self setToolbarItems:[NSArray arrayWithObjects:splitspace,camera,splitspace,refresh,splitspace,reply,splitspace,compose,splitspace, nil nil]];
定义点击事件,代码如下:
- -(void)ClickToolBarButton{
- NSLog(@"你点击了!");
- }
最终运行效果图如下:
说明:使用[self.navigationController setToolbarItems:[NSArray arrayWithObjects:splitspace,camera,splitspace,refresh,splitspace,reply,splitspace,compose,splitspace, nil] animated:YES];添加是不起作用的。
3、自定义Toolbar,首先新建一个页面,在头文件中声明一下UIToolbar *toolbar;
在实现文件中的viewDidLoad方法中实现自定义Toolbar,实现代码如下:
- - (void)viewDidLoad
- [super viewDidLoad];
- [self.navigationController setToolbarHidden:YES animated:YES];
- //自定义的UIView
- UIButton *btn=[UIButton buttonWithType:UIButtonTypeContactAdd];
- [btn addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
- UIBarButtonItem *firstButton=[[UIBarButtonItem alloc] initWithCustomView:btn];
- [firstButton setWidth:120];
- //系统自带的view
- UIBarButtonItem *addButton=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks target:self action:nil];
- toolbar=[[UIToolbar alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-toolbar.frame.size.height-44, self.view.frame.size.width, 44)];
- [toolbar setBarStyle:UIBarStyleDefault];
- toolbar.autoresizingMask=UIViewAutoresizingFlexibleTopMargin;
- [toolbar setItems:[NSArray arrayWithObjects:addButton,firstButton,nil]];
- [self.view addSubview:toolbar];
- //Do any additional setup after loading the view from its nib.
运行以后界面如下: