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?
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 .
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.
- (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 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With