swiftuinavigationcontrolleruinavigationbarpushviewcontrollerbackbarbuttonitem

Handle Back button NavigationController to push to another ViewController


im currently working on a flow like this: First after i pressed the Login Button on LoginVC -> Push to WebViewVC -> Press Back Button on NavigationBar -> Push to a TabbarVC with also contain the webViewVC, i mean webViewVC is a tab of TabbarVC. So I wonder how can i handle the Back button in order to push to the TabbarVC, not comeback to the LoginVC. Here i would attach my screen flow:

enter image description here

The top left one is the WebViewVC. Thank you very much!


Solution

  • Add this code in the webViewVc (not the one in the tabBar). Call addBackButton in ViewDidLoad

    Note: You will need to change the image to one that you have in your assets and change the name of the TabBarVc to the one you have.

    func addBackButton(_ viewController: UIViewController)
        {
            let backButton: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "Icon_back"), style: .plain, target: self, action: #selector(self.goToTabBar))
    
            self.navigationItem.setLeftBarButton(backButton, animated: true)
        }
    
    func goToTabBar()
        {
            self.navigationController?.popViewController(animated: true)
            self.navigationController?.present(TabBarVC(), animated: true, completion: nil)
        }