How to change the UINavigationController back butt

2020-01-27 02:22发布

I have a UIViewController and I'm navigating from my first view controller to second view controller and I want to change the name of the button shown on the navigationcontroller for going back ....

SecondViewController *secondController = [[SecondViewController alloc]
                                              initWithNibName:nil
                                              bundle:NULL]; 
[self.navigationController pushViewController:secondController  animated:YES];

now in the second viewcontroller I want change the name of the button in the navigationController.

17条回答
We Are One
2楼-- · 2020-01-27 02:43

I'm on ViewController1 and going to ViewController2, If I wants to change name of back button showing on ViewController2, I will do this in ViewController2.

Swift 5

self.navigationController?.navigationBar.topItem?.title = "BackButtonTitle"

Objective-C

self.navigationController.navigationBar.topItem.title = @"BackButtonTitle";
查看更多
We Are One
3楼-- · 2020-01-27 02:44

It is very important that in view controller "Simulated Metrics" option is not selected as "Inferred".

I tried with "None" and all it's right!

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-01-27 02:44

Try like this:-

NSArray *viewControllerArr = [self.navigationController viewControllers];
// get index of the previous ViewContoller
long previousViewControllerIndex = [viewControllerArr indexOfObject:self] - 1;
UIViewController *previous;
if (previousViewControllerIndex >= 0) {
    previous = [viewControllerArr objectAtIndex:previousViewControllerIndex];
    previous.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc]
                                                 initWithTitle:@"Back"
                                                 style:UIBarButtonItemStylePlain
                                                 target:self
                                                 action:nil];
}
查看更多
Ridiculous、
5楼-- · 2020-01-27 02:46

In my case it only worked running the code on the Main Thread, like so:

dispatch_async(dispatch_get_main_queue(), ^(void) {

    self.navigationController.navigationBar.backItem.title = @"Custom Title";
});
查看更多
萌系小妹纸
6楼-- · 2020-01-27 02:46

Actually, you can change title of back button:

self.navigationItem.backBarButtonItem.title = @"NewName";
查看更多
The star\"
7楼-- · 2020-01-27 02:47

Swift 4

In your UIViewController, set this:

let backButton = UIBarButtonItem()
backButton.title = "[Your title here]"
self.navigationItem.backBarButtonItem = backButton
查看更多
登录 后发表回答