How do I change the back button on a UINavigationC

2019-06-09 05:23发布

问题:

In the view I want to change it for I have the following code but it fails.

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //Logout button
    UIBarButtonItem * logout = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(goBack)];
    logout.title = @"Logout";
    nav_delegate.navigationController.navigationItem.leftBarButtonItem = logout;
    [logout release];
}

Thank you for any help.

回答1:

Implementing backBarButtonItem is for the super view controller which uses pushViewController:subViewController.

For example, if you've pushed a view controller for its super view controller Logout:

[self.navigationController pushViewController:subViewController animated:YES];

Then, you should've implemented backBarButtonItem in the super view, which is Logout view, NOT in the pushed subViewController.

So, to implement backBarButtonItem, you do it in super view Logout, like:

self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:logoutViewTitle style:UIBarButtonItemStyleBordered target:nil action:nil];

You can do this in -(void)viewDidLoad for static use, or in -(void)viewWillAppear:(BOOL)animated for dynamic use, for setting the title without allocating and initializing.

One more tip: In interface builder, there is input field for backBarButtonItem title. But if you didn't enter, you must allocate and initialize the backBarButton with title in .m files, like the code above. If you've entered the title for static use, I believe you can change it simply by using:

[self.navigationItem.backBarButtonItem setTitle:logoutViewTitle];

Hope it helped.



回答2:

Set the backBarButtonItem on the previous view controller (the one that you will return to when you press the back button).



回答3:

Here's the answer. In the view controller:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"X";
    //Logout button
    UIBarButtonItem * logout = [[UIBarButtonItem alloc] initWithTitle:@"Logout" style: UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    self.navigationItem.leftBarButtonItem = logout;
    [logout release];
}