開發過程中,UIToolbar和UINavigationBar中添加的多個UIBarButton距離都是固定不可以調整,例如在ios7以後,如果在UINavigationBar的左側添加兩個以上UIBarButton的時候,後面添加的button會覆寫[遮擋]前一個button。
因而在開發iPhone應用程式時,開發者通常使用UISegmentedControl來替代使用兩個button。
其實如果利用一下UIToolbar的一些特性就可以實作對的UIBarButton的間距調整,思路如下:
1.定義一個UIToolbar來存放兩個button
2.在兩個Button之間添加一個UIBarButtonSystemItemFlexibleSpace類型的button【為了它們之間的間隔】
3.調整UIToolbar的寬度,就可以直接調整兩個button之間的寬度了
4.将UIToolbar添加到Navigationbar中去
第4步,采用早期ios4時候添加多個UIBarButton到UIToolbar和UINavigationBar的方法即可
實作代碼如下:
//留言按鍵
UIBarButtonItem *Write = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose target:self action:@selector(AddConment)];
//搜素按鍵
UIBarButtonItem *Search = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(Search)];
//空格間距
UIBarButtonItem *Space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:@selector(Search)];
//建立一個工具欄
UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 100,44)];
//将控件添加到工具欄上面
toolbar.items = [NSArray arrayWithObjects:Write,Space,Search,nil];
//删除邊框
for (UIView *view in [toolbar subviews]) {
if ([view isKindOfClass:[UIImageView class]]) {
[view removeFromSuperview];
}
}
//在導航欄上面添加工具欄
[self.navigationController.visibleViewController.navigationController.navigationBar addSubview:toolbar];