Search code examples
iphoneobjective-cuinavigationbaruibarbuttonitemuitoolbar

UIBarButtonItem Offset?


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?


Solution

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