Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Navigation bar back button without stretching

I'm trying to replace the default nav bar back button image:

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 get is this: enter image description here

What I want is this: enter image description here

How? The original image is 11x44 points.

EDIT: After applying this,

[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 down so that it's vertically aligned with the title text in the navigation bar, to no avail. I've seen other threads with the same problem, but no solution. Why would this be so difficult? It seems like something everyone who replaces the back button image would have to deal this.

like image 210
soleil Avatar asked Dec 06 '25 08:12

soleil


1 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];
}

Don't forget to put the 3 images 1x, @2x and @3x in your image assets.

Please check the UIElements at apple document for back button.

Thanks!

like image 161
Ashish Kakkad Avatar answered Dec 07 '25 20:12

Ashish Kakkad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!