iOS 8 Custom Back Button

Eli Whittle picture Eli Whittle · Dec 29, 2014 · Viewed 8.7k times · Source

I made an app in iOS 7 and when I switched to Xcode 6.1 & iOS 8.1 my custom back buttons no longer appeared and they instead just showed the previous view controllers title--which is the default.

I am using:

self.navigationItem.backBarButtonItem.title = @"";
self.navigationItem.backBarButtonItem.tintColor = [UIColor whiteColor];

This is no longer working, I made sure to set delegates... (in .h & .m respectively)

.h

<UINavigationControllerDelegate, UINavigationBarDelegate>

.m

 self.navigationController.delegate = self;

I don't know if you do this differently in iOS8, I searched the boards and could only seem to figure out how to hide the back button. I know you have to set the back button text in the parent VC so to cover myself I included identical code in both VCs.

This code works so I know I have some ability to communicate with my navbar so it isn't like I have a problem there...

self.navigationItem.title = @"New <type>";

Thanks

Answer

Alex picture Alex · Dec 29, 2014

Sometimes with barButtonItems you need to just make new ones, instead of modifying old ones. I tried your code and it did not work for me either. This worked

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] init];
    item.title = @"Title";
    self.navigationItem.backBarButtonItem = item;
}

EDIT

This code needs to be in the previous view controller, not the view controller that has the back button. Ex. If viewController A segue's to viewController B and you want the back button on view controller B to say "Backy" instead of viewController A's title, then you actually put this code in viewController A, not viewController B

EDIT 2

To dynamically change the back button title of the view controller, replace the backBtn before you push a viewController, and give it the appropriate title.

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    let barBtnItem = UIBarButtonItem()
    navigationItem.backBarButtonItem = barBtnItem
    if segue.identifier == "seg1" {
        barBtnItem.title = "Hello 1"
    } else if segue.identifier == "seg2" {
        barBtnItem.title = "Hello 2"
    }
}