您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 實作:用 UIBarButtonItem 為導航欄加上左右按鈕

編輯:iOS 相關資訊

前言

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 的選單裡。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved