The following code works up through iOS 6:
UIButton *myButton = nil;
myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.bounds = CGRectMake(0,0,44,30);
// setup myButton's images, etc.
UIBarButtonItem *item = nil;
item = [[UIBarButtonItem alloc] initWithCustomView:customButton];
This is how the button is supposed to be aligned:
However, on iOS 7, the button appears to be offset from the right or left by too many pixels:
How can I get my custom bar button items to be aligned properly?
Change the following for your
UIButton
Not a huge fan of subclassing
UIButton
or method swizzling from Marius's answer: https://stackoverflow.com/a/19317105/287403I just used a simple wrapper, and moved the button's frame's x in a negative direction until I found the correct positioning. Button tapping appears to be fine as well (although you could extend the width of the button to match the negative offset if you needed).
Here's the code I use to generate a new back button:
Tested in iOS 11
I have tried all of the answers above and nothing worked for me. And here is what works, if anyone would need this:
-Take a look at the result.
I would like to add to @jaredsinclair confirmed answer the below override methods to those who have text and/or image in their navigation button, otherwise the text and the image won't be aligned (only the background image):
p.s. the macro is:
A better solution without jumping buttons arround can be found here:
Custom UIBarButtonItem alignment off with iOS7