skip to Main Content

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.

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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, i.e. 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
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search