简体   繁体   中英

Change tabbar selected index

I need to change tabbar selected item when view updates. So, i have tabbar with 4 items, i want that when clicking on the button that is in the last index, view updates and selected item also stays the last(3). But when i am clicking on the button, the selected item changes and it shows firstviewcontroller. I am using this code in button click

let tabBarVC = UIStoryboard(name: "TabBarViewController", bundle: nil).instantiateViewController(withIdentifier: "CustomTabBarViewController") 
let nav = UINavigationController(rootViewController: tabBarVC)
nav.setAsRoot()

When i set selected item to 3 in CustomTabBarViewController 's viewDidload it is okay, but i need that when clicking on button that works not always when tabbar is showing.

If you need to refresh all the vcs

let tabBarVC = UIStoryboard(name: "TabBarViewController", bundle: nil).instantiateViewController(withIdentifier: "CustomTabBarViewController") as! CustomTabBarViewController
tabBarVC.selectedIndex = 3
let nav = UINavigationController(rootViewController: tabBarVC)
nav.setAsRoot()

But if you need to refresh only the last vc then

let tabBarVC = self.tabBarController as! CustomTabBarViewController
let vc = // load only 3rd vc from storyboard with it's identifier
tabBarVC.viewControllers![3] = vc

The basic idea is that the tabBarController:shouldSelectViewController: selector in your UITabBarController delegate is called whenever the user clicks on tab item.

Thus, by appropriately defining that method, you get a chance to do your own processing before the current view controller is replaced by the one the user selected by clicking in the tab bar.

So, simply return NO from this selector in case you wish to prevent the current view controller to be replaced, ie when a transaction is ongoing.

import UIKit

class TabBarViewController: UITabBarController, UITabBarControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self // Delegate self to handle delegate methods.
    }

    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        let selectedIndex = tabBarController.viewControllers?.firstIndex(of: viewController)!
        if selectedIndex == 3 { // <- The index for which you don't want to set view.
            // Do anything. 
            return false
        }
        return true
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM