Disabling back button and put Cancel button in nav

2019-03-16 15:23发布

问题:

I have a navigation view controller and there are 3 view controllers in the navigation stack. Now on the third and top most visible view controller I have a default back button coming in.

I need to bring this view controller in edit mode which I did... Now the requirement is to have a cancel button as the left bar button item instead of back button.

This is similar to the functionality given by contacts application of iPhone where you edit a particular contact.

Any clue how to achieve this?

回答1:

To hide back button and add a left bar button use-

[self.navigationItem setHidesBackButton:TRUE];

    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector()];
    [self.navigationItem setLeftBarButtonItem:leftBarButton];
    [leftBarButton release];

And then to programmatically return to the previous view controller, you can do-

[self.navigationController popViewControllerAnimated:YES];


回答2:

This is a simpler way:

[self.navigationItem setHidesBackButton:YES];


回答3:

If you are using storyboard, you can also just drag a bar button item onto the navbar where the back button would normally show up. This will override it.