web-dev-qa-db-ja.com

戻るボタンがない場合は、左バーボタンアイテムをUINavigationControllerに追加します

デフォルトの左バーボタンアイテムをナビゲーションバーに追加したいのですが。 UINavigationControllerによって提供される戻るボタンがない場合にのみ表示されます。

最善のアプローチは何ですか?

19
bbrame
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if(navigationController.viewControllers.count != 1) { // not the root controller - show back button instead
        return;
    }
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize
                                                                              target:self
                                                                              action:@selector(menuItemSelected:)];   
    [viewController.navigationItem setLeftBarButtonItem:menuItem]; 
}
33
Jef

Swift 3バージョン:

let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(YourController.done))
navigationItem.setLeftBarButtonItem(done, animated: false)
3
Arsen

leftBarButtonItem…を追加するための迅速なコード

    let leftMenuItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "leftMenuItemSelected:");
    self.navigationItem.setLeftBarButtonItem(leftMenuItem, animated: false);
2

Swift 4

let item = UIBarButtonItem(title: "Setting", style: .done, target: self, action: #selector(setting))

 navigationItem.rightBarButtonItem = item

// then do your action in function setting 

@objc
  final func setting() {
    print("Your work here.")
  }
0
Mao Chenda

Swift 4.x以降(5.x)の場合

func addNavigationItemBtn(){
    let backBtn = UIBarButtonItem.init(title: "Menu", style: .plain, target: self, action: #selector(menuAction))
    self.navigationItem.leftBarButtonItem = backBtn
}

@objc func menuAction(){
    print("menu button pressed")  //Do your action here
}
0
Ashu