1

I am trying to call the UIBarButtonItem when the back button of that controller is pressed.This is my code.I have put the initialization in viewDidLoad and viewWillAppear but the method is not being called.

UIBarButtonItem *exampleButton = [[UIBarButtonItem alloc] initWithTitle:@" " style:UIBarButtonItemStylePlain target:self action:(@selector(backToViewController:))];

self.navigationItem.backBarButtonItem = exampleButton;

-(void)backToViewController:(UIBarButtonItem*)sender
 {
     [self.navigationController popToRootViewControllerAnimated:YES];
 }
tounaobun
  • 14,570
  • 9
  • 53
  • 75
soldiershin
  • 1,612
  • 1
  • 18
  • 29
  • Does the button show up correctly? Give the button an actual title so you can see it. – keithbhunter May 26 '15 at 11:43
  • You could also call self.navgiationController popToRootViewController in viewWillDisappear. That would do the same. –  May 26 '15 at 11:46
  • Set your `exampleButton` as leftBarButtonItem. – Anusha Kottiyal May 26 '15 at 11:46
  • 1
    The `backBarButtonItem` of a view controller is *not* shown in the view controller itself, it is shown in any view controller that is *on top of it* on the stack. This is because the back button usually shows the title of the *previous* view. – omz May 26 '15 at 11:47
  • @keithbhunter i tried that the title shows up in the next controller for some reason – soldiershin May 26 '15 at 11:49
  • 1
    @soldiershin Check out [this previous question](http://stackoverflow.com/questions/4964276/self-navigationitem-backbarbuttonitem-not-working-why-is-the-previous-menu-st). – keithbhunter May 26 '15 at 11:55

1 Answers1

1

IT will not add backBarButtonItem with your line as :

self.navigationItem.backBarButtonItem = exampleButton;

You have to Provide leftbarbutton as

UIBarButtonItem *exampleButton = [[UIBarButtonItem alloc] initWithTitle:@"  " style:UIBarButtonItemStylePlain target:self action:(@selector(backToViewController:))];
// As you are going with  "  ", there is no text, that means you have to click at left side randomly, to get affect.
self.navigationItem.leftBarButtonItem = exampleButton;

Update 1

You can provide Custom button with Image created by you, as you want,

UIButton *barCutomBtn =  [UIButton buttonWithType:UIButtonTypeCustom];
[barCutomBtn setImage:[UIImage imageNamed:@"backImage.png"] forState:UIControlStateNormal];
[barCutomBtn addTarget:self action:@selector(backToViewController:)forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *exampleButton = [[UIBarButtonItem alloc] initWithCustomView:barCutomBtn];
self.navigationItem.leftBarButtonItem = exampleButton;
Viral Savaj
  • 3,379
  • 1
  • 26
  • 39
  • Yes this worked.Also can you tell me where can i find the default white back arrow in ios? – soldiershin May 26 '15 at 11:59
  • Please check update 1 from the answer, you need to create that image as you want. With that image you can create new custom button as as you it with barbutton. – Viral Savaj May 26 '15 at 12:05