Bar Button Item not correctly aligned

2020-03-01 19:42发布

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

4条回答
够拽才男人
2楼-- · 2020-03-01 20:05

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.

查看更多
3楼-- · 2020-03-01 20:08

Unfortunately, there is not much you can do about UIBarButtonItem vertical spacing. I believe you'll have to either increase the font size of your title on the UINavigationBar (you can do this with UIAppearance also), or decrease the font size of your UIBarButtonItem.

查看更多
闹够了就滚
4楼-- · 2020-03-01 20:16

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

查看更多
不美不萌又怎样
5楼-- · 2020-03-01 20:20

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;
查看更多
登录 后发表回答