Search code examples
iosswiftuinavigationbarback-button

How to add a back button to a custom made UINavigationBar


I made a custom UINavigationBar using constraints. I am having trouble adding a back button to it. I could just make a UI Button and layer it on top, but I don't want to do that unless I have to.

Here is the relevant code used.

let navBar: UINavigationBar = {


    let myNav = UINavigationBar()

    myNav.translatesAutoresizingMaskIntoConstraints = false

    return myNav

    }()


func setUpNavBarView(){


self.navBar.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
self.navBar.topAnchor.constraint(equalTo: view.topAnchor as NSLayoutAnchor<NSLayoutYAxisAnchor>).isActive = true
self.navBar.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
self.navBar.heightAnchor.constraint(equalToConstant: 60).isActive = true

   self.navBar.barTintColor = UIColor.red

    self.navBar.isTranslucent = false


}

Solution

  • lazy var backButton: UIBarButtonItem = {
      let button = UIBarButtonItem(image: "Image", style: .plain, target: self, action: #selector(backButtonTapped))
      return button
    }()
    
    navigationItem.setLeftBarButton(backButton, animated: false)
    
    func backButtonTapped() {
       //Do transition here
    }