pjmanning
pjmanning

Reputation: 1309

Add Button to Navigation Controller

I'm pushing from a ViewController without a navigation controller to a ViewController with one.

I programmatically am creating the NavigationController, however, I'm having difficulty adding a button to the navigation bar.

func goToLocation() {
    let locationTableVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "locationProfile") as! LocationTableViewController
    locationTableVC.documentId = selectedDocumentId!

    let navigationController = UINavigationController(rootViewController: locationTableVC)

    self.present(navigationController, animated: true, completion: nil)
}

LocationTableViewController.swift

// MARK: - View Will Appear
override public func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    UIApplication.shared.statusBarStyle = .lightContent

    // Make Nav Bar Translucent and Set title font/color
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.view.backgroundColor = .clear
    self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont.systemFont(ofSize: 20, weight: .semibold)]
    self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back-arrow-white")

}

Upvotes: 0

Views: 1512

Answers (1)

Mamun
Mamun

Reputation: 131

Create a UIBarButtonItem using custom view & set it to leftBarButtonItem of navigationItem.

override func viewDidLoad() {

    super.viewDidLoad()
    let backButton = UIButton(type: .custom)
    backButton.frame = CGRect(x:0,y:0,width: 45, height:45)
    backButton.setImage(UIImage(named: "back-arrow-white"), for: .normal)
    let backBarButtonItem = UIBarButtonItem.init(customView: backButton)
    self.navigationItem.leftBarButtonItem = backBarButtonItem;

 }

Upvotes: 1

Related Questions