在 iOS 開發中,往 UIToolbar 或 UINavigationBar 添加多個 UIBarButtonItem 時,間距通常是固定不可調的。當導航列右側要放兩個以上的按鈕時,兩個按鈕加上中間的空白會佔掉大半空間,因此在 iPhone 這類窄螢幕裝置上,開發者往往被迫改用 UISegmentedControl 來取代。
但其實善用 UIToolbar 的特性,就能突破這個限制:
1. 建立一個 UIToolbar 用來承放這兩個按鈕
2. 在兩個按鈕之間插入一個 UIBarButtonSystemItemFlexibleSpace 類型的項目
3. 調整 UIToolbar 的寬度,即可直接壓縮兩個按鈕之間的空白
4. 把這個 UIToolbar 加入 navigation bar
其中第 4 步沿用 iOS 4 時期把多個 UIBarButtonItem 塞進 UIToolbar 或 UINavigationBar 的舊做法即可。
// button1
UIBarButtonItem *button1 = [[UIBarButtonItem alloc] initWithTitle:@"Button1"
style:UIBarButtonItemStyleBordered
target:nil
action:nil];
// button2
UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithTitle:@"Button2"
style:UIBarButtonItemStyleBordered
target:nil
action:nil];
// 彈性空白項
UIBarButtonItem *space = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil];
// 初始化 toolbar
UIToolbar *rightToolbar = [[UIToolbar alloc] init];
rightToolbar.items = [NSArray arrayWithObjects:button1, space, button2, nil];
// 使 button 的 tint 色與導航條一致
rightToolbar.tintColor = self.navigationController.navigationBar.tintColor;
// 調整寬度使 button 間距縮小
rightToolbar.frame = CGRectMake(220, 0, 101, 44);
// 移除背景,以便嵌入 UIToolbar 或 UINavigationBar
rightToolbar.backgroundColor = [UIColor clearColor];
for (UIView *view in [rightToolbar subviews]) {
if ([view isKindOfClass:[UIImageView class]]) {
[view removeFromSuperview];
}
}
// 加入到 navigation bar
[self.navigationController.visibleViewController.navigationItem
setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:rightToolbar]];
原理說明:UIBarButtonSystemItemFlexibleSpace 本身會自動撐開填滿可用空間,而 UIToolbar 又會依自身寬度配置項目。因此只要把 toolbar 的 frame 寬度設小,彈性空白被壓縮,兩個按鈕自然靠攏。這比 UISegmentedControl 更能保留各自獨立的點擊事件與視覺樣式。