Szymon Kuczur Szymon Kuczur - 6 months ago 168
iOS Question

How to hide iOS7 UINavigationBar 1px bottom line

I have an app that sometimes needs its navigation bar to blend in with the content.

Does anyone know how to get rid of or to change color of this annoying little bar?

On the image below situation i have - i'm talking about this 1px height line below "Root View Controller"

enter image description here

Answer

To do this, you should set a custom shadow image. But for the shadow image to be shown you also need to set a custom background image, quote from Apple's documentation:

For a custom shadow image to be shown, custom background image must also be set with the setBackgroundImage:forBarMetrics: method. If the default background image is used, then the default shadow image will be used regardless of the value of this property.

So the code is:

UINavigationBar *navigationBar = self.navigationController.navigationBar;

[navigationBar setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"]
                   forBarPosition:UIBarPositionAny
                       barMetrics:UIBarMetricsDefault];

[navigationBar setShadowImage:[UIImage new]];

This code assumes you want the image named "NavigationBarBackground" as bar background. If it's not the case, you can make the background a solid color by setting backgroundImage to [UIImage new] and assigning navigationBar.backgroundColor to the color you like.

Above is the only "official" way to hide it. But unfortunately it removes bar's translucency.

How to keep bar translucent?

To keep translucency you need another approach, it looks like a hack but works well. The hairline we're trying to remove is UIImageView somewhere under UINavigationBar. So we have to find it and hide or show it when needed.

First – declare instance variable:

@implementation MyViewController {
    UIImageView *navBarHairlineImageView;
}

Then, in viewDidLoad do:

navBarHairlineImageView = [self findHairlineImageViewUnder:navigationBar];

Method which finds the image view we need:

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
            return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

And this will do the rest of magic:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    navBarHairlineImageView.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    navBarHairlineImageView.hidden = NO;
}

Same method should also work for UISearchBar hairline.

Many thanks @Leo Natan for the original idea!

Comments