ChatGPT解决这个技术问题 Extra ChatGPT

How to hide 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"

https://i.stack.imgur.com/iE0SO.png

how to increase 1px of navigation height?

M
Mojtaba Hosseini

For iOS 13:

Use the .shadowColor property

If this property is nil or contains the clear color, the bar displays no shadow

For instance:

let navigationBar = navigationController?.navigationBar
let navigationBarAppearance = UINavigationBarAppearance()
navigationBarAppearance.shadowColor = .clear
navigationBar?.scrollEdgeAppearance = navigationBarAppearance

For iOS 12 and below:

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, a custom background image must also be set with the setBackgroundImage(_:for:) method. If the default background image is used, then the default shadow image will be used regardless of the value of this property.

So:

let navigationBar = navigationController!.navigationBar
navigationBar.setBackgroundImage(#imageLiteral(resourceName: "BarBackground"),
                                                        for: .default)
navigationBar.shadowImage = UIImage()

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

I don't want background image, just color##

You have those options:

Solid color, no translucency: navigationBar.barTintColor = UIColor.redColor() navigationBar.isTranslucent = false navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() Create small background image filled with color and use it. Use 'hacky' method described below. It will also keep bar translucent.

How to keep bar translucent?##

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

Instructions below assume you need hairline hidden only in one controller of your UINavigationController hierarchy.

Declare instance variable: private var shadowImageView: UIImageView? Add method which finds this shadow (hairline) UIImageView: private func findShadowImage(under view: UIView) -> UIImageView? { if view is UIImageView && view.bounds.size.height <= 1 { return (view as! UIImageView) } for subview in view.subviews { if let imageView = findShadowImage(under: subview) { return imageView } } return nil } Add/edit viewWillAppear/viewWillDisappear methods: override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if shadowImageView == nil { shadowImageView = findShadowImage(under: navigationController!.navigationBar) } shadowImageView?.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) shadowImageView?.isHidden = false }

The same method should also work for UISearchBar hairline, and (almost) anything else you need to hide :)

Many thanks to @Leo Natan for the original idea!


You can also just set the view of the UINavigationBar property: clipsToBounds = YES
@richarddas clipsToBounds = YES works like a charm! Thanks!
The clipsToBounds doesn't always work for some layouts. This answer worked perfect for me. Only I created a UINavigationBar subclass and used the above code to hide the shadow image in the -layoutSubview methods. Thanks!
Just to note I had problem where my iOS top status bar become translucent and I could see my table view scrolling behind the UINavigationBar. I fixed this by setting setTranslucent = NO.
In iOS 10 it seems that when viewWillAppear is called we cannot get shadowImageView
V
Vishnuvardhan

Here is the hack. Since it works on key paths might break in the future. But for now it works as expected.

Swift:

self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")

Objective C:

[self.navigationController.navigationBar setValue:@(YES) forKeyPath:@"hidesShadow"];

I’m on Xcode 8 and developer for > iOS 8 and none of the above worked for me except this one.
Also on XCode 8 and > iOS 8. This is the only answer that worked for me.
This is the only short and simple answer which worked for me for iOS 10 and Xcode 8.3.1. Thanks man.
Objective-C: self.navigationController.navigationBar.shadowImage = [UIImage new];
This isn't robust. Apple could stop using the "hidesShadow" keyPath at any moment, and your app will break as a result
R
Rick Pastoor

If you just want to use a solid navigation bar color and have set this up in your storyboard, use this code in your AppDelegate class to remove the 1 pixel border via the appearance proxy:

[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init]
                                  forBarPosition:UIBarPositionAny
                                      barMetrics:UIBarMetricsDefault];

[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];

This sets it global for EVERY nav bar in your code base ... most of the times not what you want.
C
Community

Try this:

[[UINavigationBar appearance] setBackgroundImage: [UIImage new]  
                                   forBarMetrics: UIBarMetricsDefault];

[UINavigationBar appearance].shadowImage = [UIImage new];

Below image has the explanation (iOS7 NavigationBar):

https://i.stack.imgur.com/FrQi3.png

And check this SO question: iOS7 - Change UINavigationBar border color


As Serhii said, a custom background image has to be set for shadow image to be accepted.
do this in your AppDelegate.
Great answer... Saved my day _/\_
@RPM Works great in iOS 7,8,9,10. There is the same code for viewControlles's navigation bar in medium for Swift.
setting shadow image to empty worked for Swift5!!
T
Tung Fam

The swift way to do it:

UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
UINavigationBar.appearance().shadowImage = UIImage()

It's pretty rare to get this far down the list before finding the sleekest answer. +1!
It hides the whole background of the UINavigationBar tho :/
Wrong, it hides the whole background too!
Note: you have to set the navigationBar's isTranslucent to false
The only one that worked for me without any side effects. I'm using Opaque Navigation Bar.
V
Vishnuvardhan

Wanted to add the Swift version of Serhii's answer. I created a UIBarExtension.swift with the following:

import Foundation
import UIKit

extension UINavigationBar {
    func hideBottomHairline() {
        self.hairlineImageView?.isHidden = true
    }

    func showBottomHairline() {
        self.hairlineImageView?.isHidden = false
    }
}

extension UIToolbar {
    func hideBottomHairline() {
        self.hairlineImageView?.isHidden = true
    }

    func showBottomHairline() {
        self.hairlineImageView?.isHidden = false
    }
}

extension UIView {
    fileprivate var hairlineImageView: UIImageView? {
        return hairlineImageView(in: self)
    }

    fileprivate func hairlineImageView(in view: UIView) -> UIImageView? {
        if let imageView = view as? UIImageView, imageView.bounds.height <= 1.0 {
            return imageView
        }

        for subview in view.subviews {
            if let imageView = self.hairlineImageView(in: subview) { return imageView }
        }

        return nil
    }
}

Thank you! This one should be the answer.
It works with navigationBar but doesn't work with uitoolbar
I'm finding with iOS 12 this is not working any more. :(.
Works great iOS 13
This one should be the answer. works like charm in ios 13
J
Jakub Průša

Simple solution in swift

   let navigationBar = self.navigationController?.navigationBar
    navigationBar?.setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
    navigationBar?.shadowImage = UIImage()

+1 Of all the answers, this is what finally worked for me. It didn't mess up the status bar as other answers, and it addresses the problem of changing only one of the navigation controller bars, not all the navigation bars in the project.
Swift 4.2 version: navigationBar?.setBackgroundImage(UIImage(), for: UIBarPosition.any, barMetrics: UIBarMetrics.default) navigationBar?.shadowImage = UIImage()
g
glotcha

As of iOS 13 there is a system API to set or remove the shadow

UIKit uses shadowImage and the shadowColor property to determine the shadow's appearance. When shadowImage is nil, the bar displays a default shadow tinted according to the value in the shadowColor property. If shadowColor is nil or contains the clearColor color, the bar displays no shadow.

    let appearance = UINavigationBarAppearance()
    appearance.shadowImage = nil
    appearance.shadowColor = nil
    navigationController.navigationBar.standardAppearance = appearance

https://developer.apple.com/documentation/uikit/uibarappearance/3198009-shadowimage


shadowImage and shadowColor aren't documented in UINavigationBarAppearance headers!! I'd never find it. Thanks, this solved my issues 100%
Yes it's working fine for me too in iOS 13 thank you so much @glotcha.
G
Gagandeep Gambhir

Can also be hidden from Storyboard (working on Xcode 10.1)

By adding runtime attribute: hidesShadow - Boolean - True

https://i.stack.imgur.com/xWDFa.png


V
Vishnuvardhan

In Swift 3.0

Edit your AppDelegate.swift by adding the following code to your application function:

// Override point for customization after application launch.

// Remove border in navigationBar
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)

s
samwize

After studying the answer from Serhil, I created a pod UINavigationBar+Addition that can easily hide the hairline.

#import "UINavigationBar+Addition.h"

- (void)viewDidLoad {
    [super viewDidLoad];

    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    [navigationBar hideBottomHairline];
}

J
Joe

Swift 4 //for hiding navigation bar shadow line

navigationController?.navigationBar.shadowImage = UIImage()

C
Community

pxpgraphics' solution updated for Swift 2.0

extension UINavigationBar {

    func hideBottomHairline()
    {
        hairlineImageViewInNavigationBar(self)?.hidden = true
    }

    func showBottomHairline()
    {
        hairlineImageViewInNavigationBar(self)?.hidden = false
    }

    private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView?
    {
        if let imageView = view as? UIImageView where imageView.bounds.height <= 1
        {
            return imageView
        }

        for subview: UIView in view.subviews
        {
            if let imageView = hairlineImageViewInNavigationBar(subview)
            {
                return imageView
            }
        }

        return nil
    }

}

extension UIToolbar
{

    func hideHairline()
    {
        let navigationBarImageView = hairlineImageViewInToolbar(self)?.hidden = true
    }

    func showHairline()
    {
        let navigationBarImageView = hairlineImageViewInToolbar(self)?.hidden = false
    }

    private func hairlineImageViewInToolbar(view: UIView) -> UIImageView?
    {
        if let imageView = view as? UIImageView where imageView.bounds.height <= 1
        {
            return imageView
        }

        for subview: UIView in view.subviews
        {
            if let imageView = hairlineImageViewInToolbar(subview)
            {
                return imageView
            }
        }

        return nil
    }

}

Hi, new to iOS and trying to teach myself. How do I use the extension? I have a view controller file and I put these extensions in it outside of the class scope. But then how do I call hide/showHairline()? Don't really understand how to use extensions but its used for so many solutions, but I just don't understand how they are implemented in the actual code
The extensions adds functionality to your existing classes. Any extended class, structure, enum, etc, will have these new features available to you whenever you need to use them. See more here: developer.apple.com/library/ios/documentation/Swift/Conceptual/…
hm so I should just be able to use UINavigationController().navigationBar/toolbar.hide/showBottomHairline() then no? I'm trying this but to no avail. Am I not understanding correctly?
A
Alvivi

I use a UINavigationBar extension that enables me to hide/show that shadow using the UIAppearance API or selecting which navigation bar has to hide/show that shadow using Storyboard (or source code). Here is the extension:

import UIKit

private var flatAssociatedObjectKey: UInt8 = 0

/*
  An extension that adds a "flat" field to UINavigationBar. This flag, when
  enabled, removes the shadow under the navigation bar.
 */
@IBDesignable extension UINavigationBar {
    @IBInspectable var flat: Bool {
        get {
            guard let obj = objc_getAssociatedObject(self, &flatAssociatedObjectKey) as? NSNumber else {
                return false
            }
            return obj.boolValue;
        }

        set {
            if (newValue) {
                let void = UIImage()
                setBackgroundImage(void, forBarPosition: .Any, barMetrics: .Default)
                shadowImage = void
            } else {
                setBackgroundImage(nil, forBarPosition: .Any, barMetrics: .Default)
                shadowImage = nil
            }
            objc_setAssociatedObject(self, &flatAssociatedObjectKey, NSNumber(bool: newValue),
                    objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

Now, to disable the shadow across all navigation bars you have to use:

UINavigationBar.appearance().flat = true

Or you can enable/disable this behavior using storyboards:

https://i.stack.imgur.com/99c32.jpg


@NunoGonçalves, you can think about flatAssociatedObjectKey as an unique int (treated as pointer) to identify your associated object. Here is defined by the memory address of a private var. I updated the response to add this var. See nshipster.com/associated-objects for more info.
Good solution but works only when navigation bar is set translucent to false
S
Sachin Rasane

Swift 4 Tested ONE LINE SOLUTION

In Viewdidload() Set Navigation controller's userdefault value true for key "hidesShadow"

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")

}

Working perfectly !!
U
UnRewa

Swift put this

UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarPosition: .Any, barMetrics: .Default)
UINavigationBar.appearance().shadowImage = UIImage()

in

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool

And it removes the background color also.
V
Vishnuvardhan

Another option if you want to preserve translucency and you don't want to subclass every UINavigationController in your app:

#import <objc/runtime.h>

@implementation UINavigationController (NoShadow)

+ (void)load {
    Method original = class_getInstanceMethod(self, @selector(viewWillAppear:));
    Method swizzled = class_getInstanceMethod(self, @selector(swizzled_viewWillAppear:));
    method_exchangeImplementations(original, swizzled);
}

+ (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;
}

- (void)swizzled_viewWillAppear:(BOOL)animated {
    UIImageView *shadow = [UINavigationController findHairlineImageViewUnder:self.navigationBar];
    shadow.hidden = YES;

    [self swizzled_viewWillAppear:animated];
}

@end

J
James
Slightly Swift Solution 
func setGlobalAppearanceCharacteristics () {
    let navigationBarAppearace = UINavigationBar.appearance()
    navigationBarAppearace.tintColor = UIColor.white
    navigationBarAppearace.barTintColor = UIColor.blue
    navigationBarAppearace.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
    navigationBarAppearace.shadowImage = UIImage()

}

Thanks James! I can't understand why someone down voted your answer.
if you need it, you can also adding: self.navigationController.navigationBar.translucent = false self.navigationController.navigationBar.clipsToBounds = false self.navigationController.navigationBar.shadowImage = UIImage() self.navigationController.navigationBar.backgroundColor = UIColor.blueColor()
C
Chathuranga Silva

For iOS 13+

The trick is to initialize 'UINavigationBarAppearance' with TransparentBackground. Then you could easily remove the horizontal line of the navigation bar.

let appearance = UINavigationBarAppearance()
appearance.configureWithTransparentBackground()
appearance.backgroundColor = .green // Required background color

Finally, add the appearance changes to the navigation item as the apple suggested.

self.navigationItem.standardAppearance = appearance
self.navigationItem.scrollEdgeAppearance = appearance
self.navigationItem.compactAppearance = appearance

m
makle

Solution in Swift 4.2:

private func removeHairlineFromNavbar() {
    UINavigationBar.appearance().setBackgroundImage(
        UIImage(),
        for: .any,
        barMetrics: .default)
    UINavigationBar.appearance().shadowImage = UIImage()
}

Just put this function at the first Viewcontroller and call it in viewdidload


E
Evgenii Mokeev

Two lines solution that works for me. Try to add this in ViewDidLoad method:

navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
self.extendedLayoutIncludesOpaqueBars = true

u
user3344977

Here's a very simple solution:

self.navigationController.navigationBar.clipsToBounds = YES;

The status bar area is also clipped.
g
gpbl

In iOS8, if you set the UINavigationBar.barStyle to .Black you can set the bar's background as plain color without the border.

In Swift:

UINavigationBar.appearance().translucent = false
UINavigationBar.appearance().barStyle = UIBarStyle.Black
UINavigationBar.appearance().barTintColor = UIColor.redColor()

This is the cleanest solution and best way to accomplish this. If you don't have to support < iOS 8, there's no reason not to use this answer. Thanks.
Works great. I set it in storyboard too so didn't even need any code.
Doing this gives you a very tiny white line instead of the standard shadow.
D
Diego Carrera

Simple solution – Swift 5

Create an extension: extension UIImage { class func hideNavBarLine(color: UIColor) -> UIImage? { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context?.fill(rect) let navBarLine = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return navBarLine } } Add this to viewDidLoad(): self.navigationController?.navigationBar.shadowImage = UIImage.hideNavBarLine(color: UIColor.clear)


M
Mariano Pardo

For iOS 9 users, this worked for me. just add this:

UINavigationBar.appearance().shadowImage = UIImage()

C
Community

The problem with setting a background image is it removes blurring. You can remove it without setting a background image. See my answer here.


R
Reza Shirazian

pxpgraphics's answer for Swift 3.0.

import Foundation
import UIKit

extension UINavigationBar {

  func hideBottomHairline() {
    let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
    navigationBarImageView!.isHidden = true
  }

  func showBottomHairline() {
    let navigationBarImageView = hairlineImageViewInNavigationBar(view: self)
    navigationBarImageView!.isHidden = false
  }

  private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView? {
    if view is UIImageView && view.bounds.height <= 1.0 {
      return (view as! UIImageView)
    }

    let subviews = (view.subviews as [UIView])
    for subview: UIView in subviews {
      if let imageView: UIImageView = hairlineImageViewInNavigationBar(view: subview) {
        return imageView
      }
    }
    return nil
  }
}

extension UIToolbar {

  func hideHairline() {
    let navigationBarImageView = hairlineImageViewInToolbar(view: self)
    navigationBarImageView!.isHidden = true
  }

  func showHairline() {
    let navigationBarImageView = hairlineImageViewInToolbar(view: self)
    navigationBarImageView!.isHidden = false
  }

  private func hairlineImageViewInToolbar(view: UIView) -> UIImageView? {
    if view is UIImageView && view.bounds.height <= 1.0 {
      return (view as! UIImageView)
    }

    let subviews = (view.subviews as [UIView])
    for subview: UIView in subviews {
      if let imageView: UIImageView = hairlineImageViewInToolbar(view: subview) {
        return imageView
      }
    }
    return nil
  }
}

S
Socheat

You should add a view to a bottom of the UISearchBar

let rect = searchController.searchBar.frame;
let lineView : UIView = UIView.init(frame: CGRect.init(x: 0, y: rect.size.height-1, width: rect.size.width, height: 1))
lineView.backgroundColor = UIColor.init(hexString: "8CC73E")
searchController.searchBar.addSubview(lineView)

I can't believe this is still an issue - just came across it again! But this solution is the best possible one at the moment; Thanks @Socheat
R
Ricardo LR

I Just created an extension for this... Sorry about formatting (this is my first answer).

Usage:

  override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.hideShadow = true
}

Extension:

 UINavigationController.swift
//  Created by Ricardo López Rey on 16/7/15.

import Foundation


struct UINavigationControllerExtension {
    static var hideShadowKey : String = "HideShadow"
static let backColor = UIColor(red: 247/255, green: 247/255, blue: 248/255, alpha: 1.0)
}

extension UINavigationController {

    var hideShadow : Bool {
        get {
            if let ret =  objc_getAssociatedObject(self, &UINavigationControllerExtension.hideShadowKey) as? Bool {
                return ret
            } else {
                return false
            }


        }
        set {
            objc_setAssociatedObject(self,&UINavigationControllerExtension.hideShadowKey,newValue, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))

            if newValue {


            self.navigationBar.setBackgroundImage(solidImage(UINavigationControllerExtension.backColor), forBarMetrics: UIBarMetrics.Default)

                self.navigationBar.shadowImage = solidImage(UIColor.clearColor())
            } else {
                self.navigationBar.setBackgroundImage(nil, forBarMetrics: UIBarMetrics.Default)
            }
        }
    }

    private func solidImage(color: UIColor, size: CGSize = CGSize(width: 1,height: 1)) -> UIImage {
        var rect = CGRectMake(0, 0, size.width, size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        color.setFill()
        UIRectFill(rect)
        var image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }


}

D
David West

Within AppDelegate, this has globally changed the format of the NavBar:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
    UINavigationBar.appearance().shadowImage = UIImage()
    UINavigationBar.appearance().tintColor = UIColor.whiteColor()
    UINavigationBar.appearance().barTintColor = UIColor.redColor()
    UINavigationBar.appearance().translucent = false
    UINavigationBar.appearance().clipsToBounds = false
    UINavigationBar.appearance().backgroundColor = UIColor.redColor()
    UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : (UIFont(name: "FONT NAME", size: 18))!, NSForegroundColorAttributeName: UIColor.whiteColor()] }

Haven't managed to implement anything different on a specific VC, but this will help 90% of people