UIBarButtonItem Offset?

2019-04-02 03:42发布

I am trying to offset the UIBarButtonItems in my app, I need them slightly offset due to the image I use for my navigation bar so it all lines up correctly. I have managed to do this like so:

[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:-3 forBarMetrics:UIBarMetricsDefault];
    [[UIBarButtonItem appearance] setBackgroundVerticalPositionAdjustment:-3 forBarMetrics:UIBarMetricsDefault];
    [[UIBarButtonItem appearance] setBackButtonBackgroundVerticalPositionAdjustment:-3 forBarMetrics:UIBarMetricsDefault];

I have two queries though.

  1. This stops the buttons have any highlighted state, they function but are no linger visibly pressed down. Anyway around this?

  2. More importantly, this works well pushing my buttons upwards in my nav bar, but it pushes them up in my toolbars as well at the bottom of the screen where I need the opposite, actually push them down a little. How can I handle this?

Any help always appreciated, thanks.

2条回答
Anthone
2楼-- · 2019-04-02 03:55

The tab bar item frames can be manipulated directly:

// get the handle of your tabBar (probably self.tabBarController.tabBar
for (UIView *item in tabBar.items) {
    item.frame = CGRectOffset(item.frame, 0.0, -3.0);
}

A less intrusive method for adjusting positions horizontal is to make use of bar button item fixed and flexible spaces:

// this will put three pixels between whatever items it sits between
UIBarButtonItem *fixed = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil]
fixed.width = 3.0;

Place these into your items array. So, if you'd like to separate two items by 3px, do this:

tabBar.items = [NSArray arrayWithObjects:button1, fixed, button2, nil];
查看更多
迷人小祖宗
3楼-- · 2019-04-02 04:14

Turns out I have found the solution! You can adjust these appearence attributes depending on what view your object is in using the following:

appearanceWhenContainedIn:

Instead of the standard

appearance

So I have implemented my needs like so, adjusting up and down depending on if the button is in a nav bar or toolbar:

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setBackgroundVerticalPositionAdjustment:-3 forBarMetrics:UIBarMetricsDefault];
    [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setBackButtonBackgroundVerticalPositionAdjustment:-3 forBarMetrics:UIBarMetricsDefault];

    [[UIBarButtonItem appearanceWhenContainedIn:[UIToolbar class], nil] setBackgroundVerticalPositionAdjustment:3 forBarMetrics:UIBarMetricsDefault];
    [[UIBarButtonItem appearanceWhenContainedIn:[UIToolbar class], nil] setBackButtonBackgroundVerticalPositionAdjustment:3 forBarMetrics:UIBarMetricsDefault];
查看更多
登录 后发表回答