UIBarButtonItem 是專門放在導航欄上的按鈕元件,可置於左側或右側。它支援數種系統內建樣式,也能接受任何自訂 view,彈性相當高。
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"First";
// 右側:純文字樣式
self.navigationItem.rightBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:@"Add"
style:UIBarButtonItemStylePlain
target:self
action:@selector(perFormAdd:)];
// 左側:使用系統內建的「加號」樣式
self.navigationItem.leftBarButtonItem =
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:@selector(perFormAdd:)];
}
- (void)perFormAdd:(id)paramSender {
NSLog(@"Action method got called.");
}
點擊左右任一按鈕,主控台都會輸出:
Action method got called.
透過 initWithCustomView:,UISwitch、UISegmentedControl、甚至自訂的搜尋框都能放上去:
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.title = @"Second";
UISwitch *simpleSwitch = [[UISwitch alloc] init];
simpleSwitch.on = YES;
[simpleSwitch addTarget:self
action:@selector(switchChanged:)
forControlEvents:UIControlEventValueChanged];
// 直接以 switch 作為右側 bar button item
self.navigationItem.rightBarButtonItem =
[[UIBarButtonItem alloc] initWithCustomView:simpleSwitch];
}
- (void)switchChanged:(UISwitch *)paramSender {
if ([paramSender isOn]) {
NSLog(@"Switch is on.");
} else {
NSLog(@"Switch is off.");
}
}
撥動開關時主控台輸出:
Switch is off. Switch is on.
左右兩側各自最多能放幾個 item 會依螢幕寬度與標題長度而變。若塞太多元素,標題會被截短甚至整個消失。實務上常見的替代方案是改用 rightBarButtonItems(複數)一次設定一組按鈕,或把次要功能收進 UIBarButtonSystemItemMore 的選單裡。