Search code examples
objective-cnavigationcontroller

Navigation controller back button title programmatically (no storyboard)


hei, 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)
         forControlEvents:UIControlEventTouchUpInside];
    [closeButton setShowsTouchWhenHighlighted:YES];

    UIBarButtonItem *rightButton =[[UIBarButtonItem alloc] initWithCustomView:closeButton];
    self.navigationItem.rightBarButtonItem=rightButton;

Solution

  • 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.

    Obj-C:

    #define NAVBAR_BUTTON_BACK      @"Back"
    
    UIBarButtonItem * nextBack = [[UIBarButtonItem alloc]
                                      initWithTitle:NAVBAR_BUTTON_BACK
                                      style:UIBarButtonItemStyleBordered
                                      target:nil action:nil];
        self.navigationItem.backBarButtonItem = nextBack;
        [nextBack release];
    

    Swift:

    navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)