デフォルトの左バーボタンアイテムをナビゲーションバーに追加したいのですが。 UINavigationControllerによって提供される戻るボタンがない場合にのみ表示されます。
最善のアプローチは何ですか?
- (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];
}
Swift 3バージョン:
let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(YourController.done))
navigationItem.setLeftBarButtonItem(done, animated: false)
leftBarButtonItem
…を追加するための迅速なコード
let leftMenuItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "leftMenuItemSelected:");
self.navigationItem.setLeftBarButtonItem(leftMenuItem, animated: false);
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.")
}
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
}