UIBarButtonItem appearance and setBackButtonBackgroundImage

18,283

Use the following code to put the image in position.

int imageSize = 20; //REPLACE WITH YOUR IMAGE WIDTH

UIImage *barBackBtnImg = [[UIImage imageNamed:@"NavBackButton"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, imageSize, 0, 0)];

[[UIBarButtonItem appearance] setBackButtonBackgroundImage:barBackBtnImg 
                                                  forState:UIControlStateNormal 
                                                barMetrics:UIBarMetricsDefault];

You can use resizableImageWithCapInsets to specify which pixels should not be stretched. If you put your image-width in there it won't stretch your image.

You don't have to put it in the .m file btw. (You could use the appDelegate.m file) just make sure it get's called before the NavigationBar is drawn.

Share:
18,283

Related videos on Youtube

Diffy
Author by

Diffy

Updated on June 04, 2022

Comments

  • Diffy
    Diffy almost 2 years

    I change my back button when pushing a new viewcontroller in my navigationcontroller. But it doesnt look nice and its stretched. Also, how can I remove the "News" title in my back button? here's my code. see the image

    screen shoot

    and the code is

    [[UIBarButtonItem appearance] setBackButtonBackgroundImage:[UIImage imageNamed:@"back_button.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    

    I want to achieve something like this http://i228.photobucket.com/albums/ee262/romano2717/photo4.png

  • Diffy
    Diffy over 12 years
    When I add this code the back button is gone after pushing the new viewcontroller to the navigation.
  • Cyrille
    Cyrille over 11 years
    This crashes with -[_UIBarItemAppearance setBackBarButtonItem:]: unrecognized selector sent to instance 0x208448d0 on 6.0.1
  • ArdenDev
    ArdenDev about 11 years
    any idea how to remove the title ??
  • Tieme
    Tieme about 11 years
    Sure: [[self navigationItem] setTitle:nil];
  • Tieme
    Tieme about 11 years
    Or do you mean the button's title?
  • dulgan
    dulgan almost 11 years
    I'd like to know the trick to remove the buttons title for back button in the whole app ;)
  • Munna89
    Munna89 over 10 years
    try [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-99, -99) forBarMetrics:UIBarMetricsDefault];
  • Morkrom
    Morkrom over 8 years
    ^ title position adjustment is NOT a good UIAppearance solution... the back button's frame is still set for it's title, resulting in misalignment issues on smaller screens.