Search code examples
iosswiftxcodeuinavigationcontrolleruibarbuttonitem

Navigate from Bar Button item to navigation controller


I have a view controller with bar button item, and an action on this button to navigate from the view to another navigation view controller, but when I navigate to the navigation controller the navigation bar is hidden!

my navigation code

guard let window = UIApplication.shared.keyWindow else { return }
    let sb = UIStoryboard(name: "Main", bundle: nil)
    let vc = sb.instantiateViewController(identifier: "AdPostViewController")
    window.rootViewController = vc
    UIView.transition(with: window, duration: 0.5, options: .transitionCrossDissolve, animations: nil, completion: nil)

to clarify I did not declare isNavigationBarhidden in the code, I am embedding a view controller to navigation controller, and when I navigate from the main view controller to the navigation controller I see the bar is hidden and I want to show it


Solution

  • I recommend not to change window.rootViewController but to present the view controller with:

    func present(_ viewControllerToPresent: UIViewController, 
        animated flag: Bool, 
      completion: (() -> Void)? = nil)
    

    Your code become:

            let sb = UIStoryboard(name: "Main", bundle: nil)
            let vc = sb.instantiateViewController(identifier: "AdPostViewController")
            vc.modalTransitionStyle = .crossDissolve
            self.present(vc, animated: true, completion: nil)
    

    Edit: And you should check if AdPostViewController is the identifier of the navigationController in your Storyboard.