Search code examples
iosobjective-cselectoruinavigationitemuinavigationcontroller

How to add a button to a UINavigation item?


I am converting an app that is written in ios 2 to ios 9. I am not really familiar with ios 2 and I need some help. Back in ios 2 there were no view controllers and xib files were used. There was one xib file called the main window which would hold all the navigation items. In my case the main window xib has a navigation bar. And in code there is the following line

self.navigationItem.title = @"Back";

So I could see when i run the app on a simulator, in one of my views there is a button with titled "Back". But i cannot find a method for this button. Like there is no IBAction for it or a method. I am trying to add a selector for the navigationitem but it doesn't work. This is what I tried:

self.navigationItem.selector = @selector(backButtonClicked:)

How can I add a selector to a navigationItem so I can search that in the project or create my own selector.


Solution

  • You can add custom back button to your navigation bar this way

    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(backButtonClicked:)];
    self.navigationItem.leftBarButtonItem = btn;
    
    
    -(void)backButtonClicked: (id)sender
    {
        [self.navigationController popViewControllerAnimated: YES]; // or popToRoot... if required.
    }