[Solved] Navigation bar with shadow & corner radius


Here is the code,

    // 1. Enable prefersLargeTitles and title
    self.navigationController?.navigationBar.prefersLargeTitles = true
    self.title = "Title"

    // 2. Add left, right bar buttons
    let leftBtn = UIBarButtonItem(title: "Edit", style: .done, target: self, action: #selector(item))
    let rtBtn = UIBarButtonItem(title: "Add", style: .done, target: self, action: #selector(item))

    self.navigationItem.rightBarButtonItem = rtBtn
    self.navigationItem.leftBarButtonItem = leftBtn

    //3. Change default navbar to blank UI
    self.navigationController?.navigationBar.isTranslucent = false
    self.navigationController?.navigationBar.tintColor = UIColor.orange

    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.backgroundColor = UIColor.white

    //4. Add shadow and cirner radius to navbar
    let shadowView = UIView(frame: CGRect(x: 0, y: -20,
                                       width: (self.navigationController?.navigationBar.bounds.width)!,
                                       height: (self.navigationController?.navigationBar.bounds.height)! + 20))
    shadowView.backgroundColor = UIColor.white
    self.navigationController?.navigationBar.insertSubview(shadowView, at: 1)

    let shadowLayer = CAShapeLayer()
    shadowLayer.path = UIBezierPath(roundedRect: shadowView.bounds, byRoundingCorners: [.bottomLeft , .bottomRight , .topLeft], cornerRadii: CGSize(width: 20, height: 20)).cgPath

    shadowLayer.fillColor = UIColor.white.cgColor

    shadowLayer.shadowColor = UIColor.darkGray.cgColor
    shadowLayer.shadowPath = shadowLayer.path
    shadowLayer.shadowOffset = CGSize(width: 2.0, height: 2.0)
    shadowLayer.shadowOpacity = 0.8
    shadowLayer.shadowRadius = 2

    shadowView.layer.insertSublayer(shadowLayer, at: 0)

Output:

enter image description here

Edit

You can get height dynamically using

self.navigationController?.view.safeAreaInsets.top

it will return 44 for iPhone X and 20 for iPhone 8

Code

var offset : CGFloat = (self.navigationController?.view.safeAreaInsets.top ?? 20)

let shadowView = UIView(frame: CGRect(x: 0, y: -offset,
                                   width: (self.navigationController?.navigationBar.bounds.width)!,
                                   height: (self.navigationController?.navigationBar.bounds.height)! + offset))

Output iPhoneX

enter image description here

4

solved Navigation bar with shadow & corner radius