Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a left bar button item to UINavigationController when no back button is present

Tags:

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?

like image 410
bbrame Avatar asked Feb 19 '14 18:02

bbrame


People also ask

How do I add a left bar button in Swift?

You need to open the storyboard, delete the view controller that you have, press cmd , shift , l , and then search for navigation controller . Drag that onto the storyboard. You now need to click on the navigation controller and set it to be the is initial view controller under the attributes inspector .

How do I make my back button invisible?

Way 1: Touch “Settings” -> “Display” -> “Navigation bar” -> “Buttons” -> “Button layout”. Choose the pattern in “Hide navigation bar” -> When the app opens, the navigation bar will be automatically hidden and you can swipe up from the bottom corner of the screen to show it.


2 Answers

- (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];  } 
like image 135
Jef Avatar answered Sep 30 '22 21:09

Jef


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); 
like image 38
Suryakant Sharma Avatar answered Sep 30 '22 19:09

Suryakant Sharma