Replacing a navigation bar button without stretching

I'm trying to replace the image of a back button in the default navigation bar:

UIImage *backButtonImage = [UIImage imageNamed:@"back_button"] ;

backButtonImage = [backButtonImage resizableImageWithCapInsets:UIEdgeInsetsMake(0, backButtonImage.size.width, 0, 0)];

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

      

What I am getting is: enter image description here

I want this: enter image description here

How? The original image is 11x44 pixels.

EDIT: after applying this parameter

[UINavigationBar appearance].backIndicatorImage = backButtonImage;
[UINavigationBar appearance].backIndicatorTransitionMaskImage = backButtonImage;

      

I get this: enter image description here

I've spent hours trying to get the arrow to move downward so that it is vertically aligned with the title text in the nav bar, to no avail. I have seen other threads with the same problem but no solution. Why is it so hard? It seems that everyone who replaces the inverse image of the button will have to deal with this.

+3


source to share


2 answers


Try this code:

UIImage *backBtnIcon = [UIImage imageNamed:@"backNavIcon.png"];

if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0)) {
    [UINavigationBar appearance].backIndicatorImage = backBtnIcon;
    [UINavigationBar appearance].backIndicatorTransitionMaskImage = backBtnIcon;
}
else{
UIImage *backButtonImage = [backBtnIcon resizableImageWithCapInsets:UIEdgeInsetsMake(0, backBtnIcon.size.width - 1, 0, 0)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:backButtonImage  forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -backButtonImage.size.height*2) forBarMetrics:UIBarMetricsDefault];
}

      

Remember to put 3 images 1x, @ 2x and @ 3x in your images.



Please check the UIElements in the apple for back doc.

Thank!

+4


source


You can create a new UIImage using the base CGContextRef on your image @ "back_button", draw a 1 point width transparent space to the right of it so you can call resizableImageWithCapInsets:UIEdgeInsetsMake(0, backButtonImage.size.width - 1, 0, 0)

.



+1


source







All Articles