Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a custom left back button on UINavigationBar WITH the standard arrow on the left

When I create a custom back button, I use the following code:

    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithTitle:@"Yeah" style:UIBarButtonItemStyleBordered target:self action:@selector(backButtonPressed:)]; self.navigationItem.leftBarButtonItem = leftButton; 

This works fine, and I obtain this result:

Screenshot of the word 'Details' where the back button would normally be.

I would have the same result, but with an arrow on the left, like this (when it's a standard back button, not a custom one):

Screenshot of the standard back arrow followed by the word 'Details'.

How can I simply add this arrow ?

like image 691
Jonathan F. Avatar asked Oct 31 '13 13:10

Jonathan F.


1 Answers

Finally, here's the snippet I use to define the back button's title with the standard left arrow in the current view, not in the parent view :

- (void)viewDidLoad {     [super viewDidLoad];      [self setTitle:@"Current View"];      // Get the previous view controller     UIViewController *previousVC = [self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 2];      // Create a UIBarButtonItem     UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"FooBar" style:UIBarButtonItemStyleBordered target:self action:@selector(yourSelector)];      // Associate the barButtonItem to the previous view     [previousVC.navigationItem setBackBarButtonItem:barButtonItem]; } 

Here's the result :

enter image description here

Note : However, since it's not possible to add an action on a backBarButtonItem, you can refer to this great post if you want it to.

Updated for Swift

// Prev - no chevron... //navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Back !", style: .plain, target: self, action: #selector(backPressed))  // adds the chevron let vc = navigationController?.viewControllers.first let button = UIBarButtonItem(title: "Go Back", style: .plain, target: self, action: #selector(backPressed)) vc?.navigationItem.backBarButtonItem = button 
like image 121
Jonathan F. Avatar answered Nov 09 '22 12:11

Jonathan F.