iosobjective-cios7uinavigationbaruibarbuttonitem

UIBarButtonItem with custom view not properly aligned on iOS 7 when used as left or right navigation bar items


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:

Normal positioning

However, on iOS 7, the button appears to be offset from the right or left by too many pixels:

Incorrect positioning on iOS 7

How can I get my custom bar button items to be aligned properly?


Solution

  • 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:

    - (UIEdgeInsets)alignmentRectInsets {
        UIEdgeInsets insets;
        if (IF_ITS_A_LEFT_BUTTON) {
            insets = UIEdgeInsetsMake(0, 9.0f, 0, 0);
        } 
        else { // IF_ITS_A_RIGHT_BUTTON
            insets = UIEdgeInsetsMake(0, 0, 0, 9.0f);
        }
        return insets;
    }
    

    Special thanks to @zev for suggesting I try adjusting alignmentRectInsets.