Search code examples
iosswiftuinavigationbar

Setting back button when presenting a view controller


On clicking a button I display a view controller using the following code:

let navController = UINavigationController(rootViewController: locationVC)
navController.navigationBar.barTintColor = StyleHelper.navBarColor()
navController.navigationBar.tintColor = UIColor.whiteColor()               
navController.navigationItem.backBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_arrow"), style: .Plain, target: locationVC, action: nil)
self.presentViewController(navController, animated: true, completion: nil)

But the back button does not appear on the locationVC

What am I doing wrong? Please help


Solution

  • Multiple issues with code.

    Issue 1:

    You should update viewController's bar button item and not navigationController's bar button item.

    So this is wrong

    navController.navigationItem.backBarButtonItem
    

    Whats correct

    self.navigationItem.backBarButtonItem
    

    Issue 2:

    The above code won't work because your current viewController is not pushed by any other VC so it cant show back button. What you need is leftBarButtonItem

    So in your VC you can write

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Abcd", style: .done, target: self, action: yourSelectorHere)
    }
    

    O/P:

    enter image description here