Home > OS >  Add UIViewController made via storyboard to TabBarController.setViewControllers
Add UIViewController made via storyboard to TabBarController.setViewControllers

Time:12-24

I am failing to understand the fundamentals of what is needed to add my HomeViewController (UIViewController) as one of the tabs in my homeTabBarController (UITabBarController) using the setViewControllers method.

I have tried initializing this and simply adding it as a param in the method. There seems to be a difference between a view controller created via storyboard and one created programmatically because when I tried adding a viewcontroller:UIViewController programmatically to the setViewControllers method, it worked fine.

My code below compiles however I get a runtime exception Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ff7b8491598) at the line when homeTabBarController.setViewControllers is called

`

    func loadTabBar() {
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let homeViewController = storyboard.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? HomeViewController

        homeViewController!.title = "Home"

        homeTabBarController.setViewControllers([homeViewController!], animated: false)
        homeTabBarController.modalPresentationStyle = .fullScreen
        present(homeTabBarController, animated: true)
    }

`

CodePudding user response:

  //MARK: - Create the instances of ViewControllers
    let grayViewController = HomeViewController()
    let blueViewController = FirstViewController()
    let brownViewController = SecondViewController()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //set title of the viewcontrollers
        grayViewController.title = "home"
        blueViewController.title = "first"
        brownViewController.title = "second"
        
        //Assigne the viewcontrollers to the TabBarViewController
        self.setViewControllers([ grayViewController, blueViewController, brownViewController], animated: false)
        
        //set system images to each tabBars
        guard let items = self.tabBar.items  else {
            return
        }
        
        let images = ["house.fill", "star.fill", "bell.fill"]
        
        for i in 0...2 {
            items[i].image = UIImage(systemName: images[i])
        }
        
        self.tabBar.tintColor = .black
        
    }

// You can download the project from the below github link


https://github.com/ahmetbostanciklioglu/AddingTabBarControllerProgrammatically.git
  • Related