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?