mpc75
mpc75

Reputation: 989

How do I create a custom UINavigationBar with the bottom two corners rounded?

I've gotten the navigation bar to round only the bottom two corners but when I use clipsToBounds = true, it clips the top of the navigation bar as well. In the image below, I want the entire bar to be orange but only a portion of it is orange.

navBar

import UIKit

class MyNavBar: UINavigationBar {

override init(frame: CGRect) {
    super.init(frame: frame)
    setupNavBar()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupNavBar()
}

func setupNavBar() {
    tintColor = .white
    barTintColor = .orange
    layer.cornerRadius = 20
    layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
    clipsToBounds = true
    }
}

Upvotes: 1

Views: 1430

Answers (2)

Jawad Ali
Jawad Ali

Reputation: 14417

You can Add this navBar as custom view in your controller to get the same look and feel

class CustomNavBar: UIView {

override init(frame: CGRect) {
    super.init(frame: frame)
    setupview()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setupview()
}

func setupview() {
    tintColor = .white
    backgroundColor = .orange
    layer.cornerRadius = 20
    layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
    clipsToBounds = true
  }
}

And i you controller baseClass

override func viewDidLoad() {
self.navigationController?.setNavigationBarHidden(true, animated: false)
    let nav = CustomNavBar()
    self.view.addSubview(nav)

   nav.translatesAutoresizingMaskIntoConstraints = false
    nav.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    nav.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    nav.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.maxX).isActive = true
    nav.heightAnchor.constraint(equalToConstant: 100).isActive = true
}

enter image description here

Upvotes: 0

Rypyak
Rypyak

Reputation: 26

You should not modify the UINavigationBar view hierarchy or alter layer properties. there is a dedicated method setBackgroundImage(_:for:barMetrics:) to customize UINavigationBar appearance. I'd suggest checking Customizing the Appearance of a Navigation Bar in Apple's UIKit Documentation here 👈.

To allow complete customization over the appearance of navigation bars, you can additionally provide custom background and shadow images. To provide a custom background image, use the setBackgroundImage(_:for:barMetrics:) method, providing a UIImage object for the appropriate bar position and metrics values.

Upvotes: 1

Related Questions