How to properly position the back button in iOS7

Bernat picture Bernat · Mar 31, 2014 · Viewed 22k times · Source

I used this code to use a custom image as the back button in the whole app.

[[UINavigationBar appearance] setBackIndicatorImage:[UIImage imageNamed:@"back"]];
[[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:[UIImage imageNamed:@"back"]];

The image dimensions are 30 x 30.

The code adds the image as the back button but the position is not the correct, as you can see in the following image:

back button not correct positioned

Any ideas on how to properly position the image without modifying its dimensions (at least the visual part of the image (circle + arrow))?

EDIT:

I don't want to use a custom back button because that forces me to disable the swipe/back-gesture in iOS7

Answer

race_carr picture race_carr · Apr 19, 2014

EDIT
I think I might have found the trick (in iOS 7 Design Resource -- UIKit User Interface Catalog.)
Under Bar Button Items

Note that a bar button image will be automatically rendered as a template image within a navigation bar, unless you explicitly set its rendering mode to UIImageRenderingModeAlwaysOriginal. For more information, see Template Images.

Under Template Images they have some code to specify the UIImageRenderingMode.

UIImage *myImage = [UIImage imageNamed:@"back"];
UIImage *backButtonImage = [myImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];  
// now use the new backButtomImage
[[UINavigationBar appearance] setBackIndicatorImage:backButtonImage];
[[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:backButtonImage];

Try creating the UIImage with alignment insets and then set the Back Indicator image.

UIEdgeInsets insets = UIEdgeInsetsMake(10, 0, 0, 0); // or (0, 0, -10.0, 0)
UIImage *alignedImage = [[UIImage imageNamed:@"back"] imageWithAlignmentRectInsets:insets];  
[[UINavigationBar appearance] setBackIndicatorImage:alignedImage];
[[UINavigationBar appearance] setBackIndicatorTransitionMaskImage:alignedImage];

You might also try adjusting the position of the UINavigationBar title text

[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics];