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?
Ok, I went the other "direction". I made everything line up properly via Storyboard with iOS 7 (assuming this is how it will continue to work). And then using the describe sub-class approach, I sub-class
UIButton
with the following implementation.So this code only runs if the device is pre-iOS 7.
Thanks for the insight @jaredsinclair!
I came up with a shortened Version of jaredsinclair's approach:
Works like a charm.
It just simply adjust
imageEdgeInsets
to fix this bug.try this.
Works until iOS11!
You can use negative flexible spaces and rightBarButtonItems property instead of rightBarButtonItem:
@jaredsinclair
Here is a look at my code.
See anything that isnt right?
Here is the result. The second image is not so visible because I had to time taking the screenshot and it is still in transition, but you can clearly see how it is improperly offset.
Good normal image:
Bad Offset Image:
After about a half second, the image then snaps back to the original image location.
Here is my code for the NavButton.h and .m:
*Solution found, read on the end of the answer.*
@jaredsinclair
I have similar case as Kyle Begeman
This is the button
and I use it in this case
Everything looks great except that, when I go back to the previous VC, the button repositions itself. Like a small jump. For me it does jump right away not after a second. And it happens after I go do the popVC from NavigationViewController.
Edit: The answer below, the swizzling method from Marius helped me as well.