Add a left bar button item to UINavigationController when no back button is present
- (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);
Swift 3 version:
let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(YourController.done))
navigationItem.setLeftBarButtonItem(done, animated: false)