Add a left bar button item to UINavigationController when no back button is present
16,541
Solution 1
- (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];
}
Solution 2
Swift code to add leftBarButtonItem
…
let leftMenuItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "leftMenuItemSelected:");
self.navigationItem.setLeftBarButtonItem(leftMenuItem, animated: false);
Update
For Swift 4 & above
let leftMenuItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(leftMenuItemSelected(_:)))
self.navigationItem.setLeftBarButton(leftMenuItem, animated: false);
Solution 3
Swift 3 version:
let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(YourController.done))
navigationItem.setLeftBarButtonItem(done, animated: false)
Solution 4
For Swift 4.x and later(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
}
Related videos on Youtube
Author by
bbrame
Updated on June 06, 2022Comments
-
bbrame almost 2 years
I'd like to add a default left bar button item to my navigation bar. It should only display when there is no back button supplied by the UINavigationController.
What is the best approach?
-
rmaddy about 10 yearsYour question is the best approach. If there is no back button, add your left button.
-
-
David Sujarwadi over 6 yearsThis is Delegate from UINavigationController?