Search code examples
swiftuikituitabbarcontroller

Change the tabs in a Embedded TabBarController


I have a view controller which has two buttons and an embedded TabBarController. I want to use the two button instead of the tab bar item. And for some reason cannot make it work.

MainView

import UIKit

class ViewController: UIViewController {
    
    var currentTab = 0
    
    @IBOutlet weak var container: UIView!
    
    @IBAction func item1Button(_ sender: UIButton) {
        currentTab = 0
    }
    
    @IBAction func item2Button(_ sender: UIButton) {
        currentTab = 1
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toControllers"{
            if let vc = segue.destination as? TabsViewController {
                vc.selectedIndex = currentTab

            }
        }
    }
}

TabBarController

import UIKit

class TabsViewController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

I have two items in the storyboard, so item 0 and 1 should be ok.

Maybe it is very simple, cannot figure it out myself.

Thank you!


Solution

  • I figure it out, here is the solution:

    Changed the main controller to:

    class ViewController: UIViewController {
        
        var currentTab = 1
        private var tabViewController: UITabBarController?
        
        @IBOutlet weak var container: UIView!
        
        @IBAction func item1Button(_ sender: UIButton) {
            print("click item1")
            tabViewController?.selectedIndex = 0
        }
        
        @IBAction func item2Button(_ sender: UIButton) {
            print("click item2")
            tabViewController?.selectedIndex = 1
        }
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
        }
    
        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if segue.identifier == "toControllers"{
                if let vc = segue.destination as? TabsViewController {
                    tabViewController = vc
                }
            }
        }