導航器是 iOS 開發中最常見的容器之一,而導航欄右側放一顆按鈕更是家常便飯:
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc]
initWithTitle:@"Setting"
style:UIBarButtonItemStylePlain
target:self
action:@selector(clickSettings:)];
self.navigationItem.rightBarButtonItem = anotherButton;
[anotherButton release];
按鈕樣式有很多種可選,包含系統內建的 Add、Done、Edit、Save、Cancel、Play、Refresh 等,搭配 initWithBarButtonSystemItem:target:action: 使用。完整清單可查閱 Apple 的 UIBarButtonItem 類別參考文件。
問題來了:rightBarButtonItem 顧名思義只收一個項目。要在一側塞進多顆按鈕,做法是把它們裝進一個 UIToolbar,再將這個 toolbar 包成一個自訂檢視的 bar button item。
UIToolbar* tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 150, 45)];
[tools setTintColor:[self.navigationController.navigationBar tintColor]];
[tools setAlpha:[self.navigationController.navigationBar alpha]];
NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:2];
UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(clickSettings:)];
UIBarButtonItem *anotherButton1 = [[UIBarButtonItem alloc]
initWithTitle:@"Edit"
style:UIBarButtonItemStylePlain
target:self
action:@selector(clickEdit:)];
[buttons addObject:anotherButton];
[anotherButton release];
[buttons addObject:anotherButton1];
[anotherButton1 release];
[tools setItems:buttons animated:NO];
[buttons release];
UIBarButtonItem *myBtn = [[UIBarButtonItem alloc] initWithCustomView:tools];
self.navigationItem.rightBarButtonItem = myBtn;
[myBtn release];
[tools release];
整段程式碼的邏輯可以拆成三步:建立一個寬度足夠的 UIToolbar;把多顆 UIBarButtonItem 放進它的 items 陣列;最後用 initWithCustomView: 把整個 toolbar 視為單一自訂檢視,交給 rightBarButtonItem。導航欄並不知道裡頭藏了幾顆按鈕,它只看到你給的一個檢視。
兩個細節決定成品好不好看:一是 tintColor 與 alpha 都從 navigationBar 同步過來,否則 toolbar 會帶著自己的預設底色,在導航欄中顯得突兀;二是 toolbar 的寬度要依按鈕數量調整,太窄會截斷,太寬會壓到標題或左側按鈕。
值得補充的是,若你的部署目標在 iOS 5 以上,UINavigationItem 提供了 rightBarButtonItems 這個陣列屬性,可直接放入多顆 bar button item,由系統負責排版間距,視覺效果通常比自製 toolbar 更貼近原生。toolbar 的寫法仍有其用途——例如需要完全自訂間距與背景時——但一般情況優先考慮系統提供的陣列屬性會更省事。
最後,上述範例為 MRC 寫法,ARC 專案請移除 release 呼叫。