UIToolbar 默認項目靠左佈局,直接添加 UIBarButtonItem 無法居中。
在目標項目左右各添加一個 UIBarButtonSystemItemFlexibleSpace,系統會自動分配剩餘空間,使中間項目居中。
Toolbar

UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UIBarButtonItem *flexLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
UIBarButtonItem *centerItem = [[UIBarButtonItem alloc] initWithTitle:@"居中標題" style:UIBarButtonItemStylePlain target:nil action:nil];
UIBarButtonItem *flexRight = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
toolbar.items = @[flexLeft, centerItem, flexRight];
// 3 個項目等寬:項目間各插一個 Flexible Space
toolbar.items = @[
item1,
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
item2,
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
item3
];
| 類型 | 行為 | 用途 |
|---|---|---|
UIBarButtonSystemItemFixedSpace | 固定寬度 (width 屬性) | 精確像素間距、分隔符 |
UIBarButtonSystemItemFlexibleSpace | 自動填充剩餘空間 | 居中、兩側對齊、等寬分佈 |
iOS 9+ 推薦使用 UIStackView 管理工具欄內容:
UIStackView *stack = [[UIStackView alloc] initWithArrangedSubviews:@[btn1, btn2, btn3]];
stack.axis = UILayoutConstraintAxisHorizontal;
stack.distribution = UIStackViewDistributionFillEqually; // 等寬
stack.alignment = UIStackViewAlignmentCenter;
stack.spacing = 0;
[toolbar addSubview:stack];
// 設置 stack 約束填滿 toolbar
優勢:動畫支援、動態增減項目、Size Class 適配、代碼更清晰。