objective-ciospushbackbarbuttonitem

How set set title to leftBarButtonItem


I have root ViewController and detailed ViewController. When i push to detailedViewController i get leftBarButtonItem with the title from the root one. But i want the title to be just "Back", nothing more. So how to do that?

This doesn't help

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

To create my on type barButtonItem(for example 104 with left arrow) and to set it to leftBarButtonItem is terrible decision.

Is there other way than to change the title of the rootViewController manually before pushing?


Solution

  • From Apple's doc:

    backBarButtonItem

    The bar button item to use when a back button is needed on the navigation bar.

    @property(nonatomic, retain) UIBarButtonItem *backBarButtonItem Discussion

    When this navigation item is immediately below the top item in the stack, the navigation controller derives the back button for the navigation bar from this navigation item. When this property is nil, the navigation item uses the value in its title property to create an appropriate back button. If you want to specify a custom image or title for the back button, you can assign a custom bar button item (with your custom title or image) to this property instead. When configuring your bar button item, do not assign a custom view to it; the navigation item ignores custom views in the back bar button anyway.

    So, you can create create your barButtonItem (e.g. ā€“ initWithTitle:style:target:action:) and assign it to that property.

    In addition, if you want to have a custom image for UIBarButtonItem (left or right) I suggest you to create a category extension like the following:

    //UIBarButtonItem+Extension.h    
    + (UIBarButtonItem*)barItemWithImage:(UIImage*)image title:(NSString*)title target:(id)target action:(SEL)action;
    
    //UIBarButtonItem+Extension.m    
    + (UIBarButtonItem*)barItemWithImage:(UIImage*)image title:(NSString*)title target:(id)target action:(SEL)action
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
        button.titleLabel.textAlignment = UITextAlignmentCenter;
    
        [button setBackgroundImage:image forState:UIControlStateNormal];
        [button setTitle:title forState:UIControlStateNormal];
        [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
        UIBarButtonItem* barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
        return [barButtonItem autorelease];    
    }
    

    and then use it as

    UIBarButtonItem* backBarButtonItem = [UIBarButtonItem barItemWithImage:[UIImage imageNamed:@"YoutImageName"] title:@"YourTitle" target:self action:@selector(doSomething:)];