iosswiftuitabbarcontrolleruitabbarpresentviewcontroller

How to show different ViewControllers when tapping on tabBar in swift


I have three viewControllers and two of them connected to a tabBarController. So app should show one of the two vc’s depending Bool value when tapping on tabBar item here is my storyboard

import UIKit

class TabBarController: UITabBarController, UITabBarControllerDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
      
        
    }
    
    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        let userLoggedIn: Bool!
        if tabBarController.selectedIndex == 1{
            if userLoggedIn == true{
                // show firstVC
            }else{
                // show secondVC
            }
        }
    }
}

Solution

  • Simply add .overCurrentContext to modalPresentationStyle in your viewDidLoad like this.

     let newVC = self.storyboard?.instantiateViewController(withIdentifier:"secondVC")
     newVC?.modalPresentationStyle = .overCurrentContext
     self.present(newVC!, animated: false, completion: nil)