toolbar 的屬性結構與先前談過的 navigationBar、navigationItem 幾乎一致,差別在於 toolbarItems 沒有左右之分——它就是一個平坦的項目清單。
工具列本身可以調整的地方不少:背景色、背景圖片、barStyle 樣式、frame 位置等。但要留意,其中有些設定實際上不會生效;而它是否顯示,最終是由 navigationController 掌控,跟 navigationBar 一樣。
真正的重點在 toolbarItems。我們平常在 App 底部看到的「首頁」、「設置」那類選項,其實都是 UIBarButtonItem,需要裝進一個陣列再整體指派給 toolbarItems(屬性名有個 s,就是這個意思)。
這裡有個特別值得認識的成員:UIBarButtonSystemItemFlexibleSpace。嚴格說它不是一個合格的按鈕,而是一塊可自由伸縮的空白區域,行為像彈簧——其他項目把它填滿時它就縮小,還有空間時它就撐大。它正是排版用的工具:若只有首尾兩個項目,只要在頭尾與中間各放一個 FlexibleSpace,兩個按鈕就會居中;若有三個,寫法同理,你自己試試就知道了。
以下範例在導航控制器的根視圖控制器上實作(記得先在 AppDelegate 中建立導航控制器,把這個 ViewController 設為 rootViewController,否則畫面不會出現):
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
// 顯示工具列,兩種寫法皆可
self.navigationController.toolbarHidden = NO;
[self.navigationController setToolbarHidden:NO animated:YES];
// 樣式設定,多為半透明效果
[self.navigationController.toolbar setBarStyle:UIBarStyleBlack];
// 背景圖片:forToolbarPosition 決定出現在何處時套用,
// barMetrics 決定豎屏或橫屏時套用
[self.navigationController.toolbar setBackgroundImage:[UIImage imageNamed:@"navigationBar.png"]
forToolbarPosition:UIBarPositionBottom
barMetrics:UIBarMetricsDefault];
// 建立各個項目
UIBarButtonItem *btn1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self action:nil];
UIBarButtonItem *btn2 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemBookmarks
target:self action:nil];
UIBarButtonItem *btn3 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCompose
target:self action:nil];
UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:self action:nil];
// 用彈簧項目把按鈕撐在中間
NSArray *items = [[NSArray alloc] initWithObjects:space, btn1, space, btn2, space, btn3, space, nil];
self.toolbarItems = items;
self.view.backgroundColor = [UIColor purpleColor];
[super viewDidLoad];
}
@end
幾個實務提醒:每個 UIBarButtonItem 的 action 要記得接上真正的 selector,範例中為求簡潔留空;若要放自訂圖片,改用 initWithImage:style:target:action: 或自訂 view 版本;而 setBackgroundImage:forToolbarPosition:barMetrics: 在橫豎屏需要分別設定時,記得再傳一次 UIToolbarPositionTop 或另一組 barMetrics。