1

I need to adjust the vertical position of my UIBarButtonItem in UINavigationBar.I think there is a way to do this. To add a UIView to UIBarButtonItem and add a UIButton to the UIView. It's ok if you have only one or two navigation bar. But I think it's a bit too troublesome if you have dozens of UINavigationBar especially inside a storyboard. So I did some researches and found a easy solution for this. That is to use category. Here is my source code:

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"

-(void)viewWillAppear:(BOOL)animated
{
    [self show:NO];
}

// do your override
-(void)viewWillLayoutSubviews
{
    [self changeTheButtonPosition:self.navigationItem.leftBarButtonItem];
    [self changeTheButtonPosition:self.navigationItem.rightBarButtonItem];
}

-(void)viewDidAppear:(BOOL)animated
{
    [self show:YES];
}

#pragma clang diagnostic pop

-(void)show:(BOOL)show
{
    self.navigationItem.leftBarButtonItem.customView.hidden = !show;
    self.navigationItem.rightBarButtonItem.customView.hidden = !show;
}

- (void)changeTheButtonPosition:(UIBarButtonItem *)barButtonItem
{
    if ( barButtonItem )
    {
        UIView* customView = barButtonItem.customView;
        //        NSLog(@"custom view frame = %@",NSStringFromCGRect(customView.frame));
        CGRect frame = customView.frame;
        CGFloat y = SYSTEM_VERSION_LESS_THAN(@"7") ? 10.0f : 5.0f;
        customView.frame = CGRectMake(frame.origin.x, y, frame.size.width, frame.size.height);
    }
}

It works perfectly in iOS 7 and in the first view controller in iOS 6. But it doesn't work for the pushed UIViewController in iOS 6. I can't find any reason for that. Can anybody advise? What's wrong in my code in iOS 6?

TylerH
  • 20,799
  • 66
  • 75
  • 101
Bagusflyer
  • 12,675
  • 21
  • 96
  • 179
  • I find another solution in http://stackoverflow.com/questions/6566216/vertically-aligning-uinavigationitems/17434530#17434530 although it's a bit more difficult than mine. – Bagusflyer Nov 15 '13 at 08:09

1 Answers1

2

You should be able to achieve this using the UIAppearance proxy methods introduced in iOS5. In particular:

- (void)setBackgroundVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics
- (void)setTitlePositionAdjustment:(UIOffset)adjustment forBarMetrics:(UIBarMetrics)barMetrics

Check the UIBarButtonItem docs for more info.

Tark
  • 5,153
  • 3
  • 24
  • 23
  • 1
    This doesn't seem to work very well in iOS 7 however. I have some problems when setting the title position there and then the OS takes over and any other adjustments to anything cause the button to move. Any orientation moves it. And the end destination is the default location. Specifically I have this problem with an edit button and trying to pin it to the top of a taller navigation bar. – cynistersix Dec 10 '13 at 01:11