UIBarButtonItem Offset?

放肆的年华 提交于 2019-12-05 04:19:18

问题


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?


回答1:


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];



回答2:


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];


来源:https://stackoverflow.com/questions/11604899/uibarbuttonitem-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!