suMi suMi - 1 year ago 154
Objective-C Question

Navigation controller back button title programmatically (no storyboard)

I'm new to navigation controllers and I've got one question for something that should be rather simple:
How do I change the "back" item on the left site to have the title "Back" instead of the title of the previous view?
I've tried this:

self.navigationItem.leftBarButtonItem.title =@"Back";

and it doesn't work, even though I can use similar code to add an image on the left, like this:

CGRect frame = CGRectMake(0, 0, 22.5, 22.5);
UIButton *closeButton = [[UIButton alloc] initWithFrame:frame];
[closeButton setBackgroundImage:UA_ICON_CLOSE_UI forState:UIControlStateNormal];
[closeButton addTarget:self action:@selector(closeView)
[closeButton setShowsTouchWhenHighlighted:YES];

UIBarButtonItem *rightButton =[[UIBarButtonItem alloc] initWithCustomView:closeButton];

Answer Source

You have to write this code in the view controller in advance, that is, when this view controller is in the view controller stack and you move to a new view controller, in the new view controller the "Back" button will be shown of top left instead of that's title.

If you write this way, self.navigationItem.leftBarButtonItem = nil or create another UIBarButtonItem, but this will not go back and did not have the nice back arrow by default. If you set in this way, this will be a button of this view controller. But you can give it an action to dismiss the view controller and go back.


#define NAVBAR_BUTTON_BACK      @"Back"

UIBarButtonItem * nextBack = [[UIBarButtonItem alloc]
                                  target:nil action:nil];
    self.navigationItem.backBarButtonItem = nextBack;
    [nextBack release];


self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style:.Plain, target:nil, action:nil)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download