Search code examples
iosswiftuitabbarcontroller

I can't change tabBar SelectedIndex


I try to change Tabbar selected item according to selected button tag.But nothing happens. This my button Control class.

class ButtonControl {
    public func controlMoreButtons(sender:UIButton){
        let board = UIStoryboard.init(name: "Main", bundle: nil)
        let tabbar = board.instantiateViewController(identifier: "mainTabBar") as! MainTabBarController
      
        let tag = sender.tag
        switch tag {
        case 1:
            tabbar.selectedIndex = 2
           print("1")
        case 2:
            print("2")
        case 3:
            print("3")
        default:
            print("unknown")
        }
        
    }
}

This is my Button action :

@IBAction func seeMoreButtonClicked(_ sender: UIButton) {
        let buttonControl = ButtonControl()
        buttonControl.controlMoreButtons(sender: sender)
        
    }

Solution

  • 1- Add

    class ButtonControl {
        weak var tab:UITabBarController?
    

    2- Then

    let buttonControl = ButtonControl()
    buttonControl.tab = self.tabBarController
    

    3- Finally

    tab.selectedIndex = sender.tag
    

    And remove this part completely as it a new instance

    let board = UIStoryboard.init(name: "Main", bundle: nil)
    let tabbar = board.instantiateViewController(identifier: "mainTabBar") as! MainTabBarController