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?
In order to fix this bug, you must subclass UIButton so that you can override
alignmentRectInsets
. From my testing, you'll need to return a UIEdgeInsets with either a positive right offset or a positive left offset, depending on the button position. These numbers make no sense to me (at least one of them should be negative, according to common sense), but this is what actually works:Special thanks to @zev for suggesting I try adjusting alignmentRectInsets.
in ios7 you can just add a dummy barbuttonitem for fixing left space you should add dummy as first, for right as last
example for left, you should add this after setting your original items or in viewdidload if you are setting buttons using storyboard.
2018, iOS 11+, Swift 4.x, this worked for me.
Combining the top answers:
Property
In
viewDidLoad
: