Tommy K
Tommy K

Reputation: 1809

Swift 3 remove line underneath navbar

When my project was in Swift 2, I had this code that worked:

extension UINavigationController {
func hairLine(hide: Bool) {
    //hides hairline at the bottom of the navigationbar

    for subview in self.navigationBar.subviews {
        if subview.isKind(of: UIImageView.self) {
            for hairline in subview.subviews {
                if hairline.isKind(of: UIImageView.self) && hairline.bounds.height <= 1.0 {
                    hairline.isHidden = hide
                }
            }
        }
    }
}

}

But now something changed and it doesn't work. Not sure if it because of Swift 3, or iOS10, or that I'm now testing with a 7plus vs a 6s, but it no longer works. I would call in it viewWillAppear of the view controller that is being shown. I saw an answer on here saying to use

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

but that hasn't worked. I tried replacing the content of my old hairLine() with those 2 lines, tried putting them directly in viewWillAppear and viewDidAppear but still doesn't work for me.

Upvotes: 2

Views: 2382

Answers (4)

Nikunj Agola
Nikunj Agola

Reputation: 484

Try this

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

Upvotes: 6

Carien van Zyl
Carien van Zyl

Reputation: 2873

Try:

self.navigationController?.navigationBar.setBackgroundImage(_:UIImage(),
        for: .any,
        barMetrics: .default)
self.navigationController?.navigationBar.shadowImage = UIImage()

in viewDidLoad()

Upvotes: 0

Wilson
Wilson

Reputation: 9136

Before:

enter image description here

After:

enter image description here

Code:

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Hello World"
    
    let navbarColor = UIColor(colorLiteralRed: (247/255), green: (247/255), blue: (247/255), alpha: 1)
    let image = UIImage()
    
    navigationController?.navigationBar.setBackgroundImage(image, for: .default)
    navigationController?.navigationBar.shadowImage = image
    navigationController?.navigationBar.backgroundColor = navbarColor
    
    let statusBarHeight = UIApplication.shared.statusBarFrame.height
    let statusBarWidth = UIScreen.main.bounds.size.width
    
    let statusBarView = UIView(frame: CGRect(x: 0, y: 0, width: statusBarWidth, height: statusBarHeight))
    statusBarView.backgroundColor = navbarColor
      
    view.addSubview(statusBarView)
  }

Upvotes: 2

Faris Sbahi
Faris Sbahi

Reputation: 666

Try this

UINavigationBar.appearance().setBackgroundImage(_:
    nil,
    for: .any,
    barMetrics: .default)

UINavigationBar.appearance().shadowImage = nil

Upvotes: -1

Related Questions