Search code examples
iphoneiosuinavigationcontrolleruinavigationitem

Custom back button on navigation bar


In my application there are many UIViewControllers with UINavigationControllers. There must be a "back" button and a "home" UIButton on the UINavigationBar. All of this works fine.

But some of my UIViewControllers have long names, and sometimes there is too small place left for it. I'm trying to replace the original label of the "back" button (it shows the title of the previous view) with a custom "Back", but whatever I tried it didn't work:

// Title didn't change
[self.navigationItem.backBarButtonItem setTitle:@"Back"];

// Action didn't set, no response from button ( button didn't do anything )
[self.navigationItem.leftBarButtonItem
   setAction:self.navigationItem.backBarButtonItem.action];

And I need the "back" button to have a style like in this question: Draw custom Back button on iPhone Navigation Bar


Solution

  • Try this

    UIBarButtonItem *backBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(popViewController)];
    [self.navigationItem setBackBarButtonItem:backBarBtnItem];
    
    - (void)popViewController
    {
        [self.navigationController popViewControllerAnimated:YES];
    }