2

I'm trying to add a drop shadow to my navigationbar. The code looks like this:

UINavigationBar.appearance().barStyle = .black
UINavigationBar.appearance().barTintColor = UIColor(white: 155/255,
                                                    alpha: 1.0)
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().layer.shadowOffset = CGSize(width: 0, height: 4)
UINavigationBar.appearance().layer.shadowRadius = 4.0
UINavigationBar.appearance().layer.shadowColor = UIColor.black.cgColor
UINavigationBar.appearance().layer.shadowOpacity = 0.4
UINavigationBar.appearance().layer.masksToBounds = false
UINavigationBar.appearance().layer.shouldRasterize = true

But it does not work. Why is it not working and what am I missing? I don't want to extend or subclass the NavigationBar to do this.

EDIT: I figured out that the

UINavigationBar.appearance().layer.bounds

returns wrong values so probably thats the case but does someone know why?

L3M0L
  • 429
  • 8
  • 23

2 Answers2

0

Try below code inside your viewDidLoad.

    navigationController?.navigationBar.layer.shadowColor = UIColor.black.cgColor
    navigationController?.navigationBar.layer.shadowOpacity = 1
    navigationController?.navigationBar.layer.shadowOffset = CGSize.zero
    navigationController?.navigationBar.layer.shadowRadius = 10
    navigationController?.navigationBar.layer.masksToBounds = false

Output:

enter image description here

Joe
  • 8,868
  • 8
  • 37
  • 59
  • 2
    Thanks! However thats not the solution I'm looking for :( I want to do it through UIAppearance so the shadow is everywhere the same. – L3M0L Mar 25 '17 at 16:53
0

Swift 3

Extend UINavigationBar and define the desired shadow property

extension UINavigationBar {

    var shadow: Bool {
        get {
            return false
        }
        set {
            if newValue {
                self.layer.shadowOffset = CGSize(width: 0, height: 2)
                self.layer.shadowColor = UIColor.lightGray.cgColor
                self.layer.shadowRadius = 3
                self.layer.shadowOpacity = 0.5;
            }
        }
    }
}

Add the shadow from AppDelegate globally as

UINavigationBar.appearance().shadow = true

Credits Amer Harb

Mathews
  • 733
  • 5
  • 11