Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bar Button Item not correctly aligned

I have an issue with my navigation bar, the UIBarButtonItem is not correctly vertically aligned. I don't know why because I'm using a simple UIBarButtonItem and not a custom view. See my code below and thanks for your help!

UIBarButtonItem *newGameItem = [[UIBarButtonItem alloc] initWithTitle:@"New Game" style:UIBarButtonItemStyleDone target:self action:@selector(newGame)];
self.navigationItem.rightBarButtonItem = newGameItem;

Screenshot navigation bar issue

like image 959
Seb Thiebaud Avatar asked May 08 '14 15:05

Seb Thiebaud


3 Answers

Actually there are couple ways to align the bar buttons. Try to adjust the button title position with this:

[self.navigationItem.rightBarButtonItem setTitlePositionAdjustment:UIOffsetMake(-10, -10) 
                                                     forBarMetrics:UIBarMetricsDefault];

-10 -10 - just for example

OR

you can initialize your newGameItem with custom UIButton. The custom button is a subclass of UIButton with this method overridden

- (UIEdgeInsets)alignmentRectInsets {
    return UIEdgeInsetsMake(0, -10, 0, 15.0f); // here you can play with values to align your button properly
}

then initialize your newGameItem

CustomBarButton *button = [CustomBarButton buttonWithType:UIButtonTypeCustom];
[button setTitle:@"New game" forState:UIControlStateNormal];
button.frame = CGRectMake (0, 0, 60, 40);
[button addTarget:self action:@selector(newGame) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *newGameItem = [[UIBarButtonItem alloc] initWithCustomView:button];
self.navigationItem.rightBarButtonItem = newGameItem;
like image 126
kas-kad Avatar answered Oct 20 '22 23:10

kas-kad


I had a similar issue: We use custom fonts via UIAppearance for both navigation titles and bar button items, and in some cases, the right item was vertically misaligned.

I could easily fix the misalignment by using [self.navigationItem setRightBarButtonItem:rightItem animated:YES] instead of the property setter.

like image 32
hagi Avatar answered Oct 21 '22 00:10

hagi


I had the same problem with a button on the left, I was able to fix it in Xcode 6.3.1: select the button (bar button item) right column tab "ruler" inset image Top value: -54 instead of 0. Note that: my device is an iPhone4 with iOS 7, the button was perfectly in place in Xcode and misplaced on the device, now it is in place on the device and misplaced in Xcode

like image 28
chairam Avatar answered Oct 21 '22 00:10

chairam