1

I have a UITabBarController with 5 tabs. By pressing on tab I want to make a simple check to determine which UIViewController my UITabBarController should show by pressing a tab.

What is the better way to do it?

Matrosov Oleksandr
  • 25,505
  • 44
  • 151
  • 277
  • you can get view controller of selected tab by tabbarController?.viewControllers?[1] as! YourViewController – Vah.Sah Apr 24 '17 at 12:03

3 Answers3

1

Try this one

-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
    //here it provide the viewController
}
Bhupat Bheda
  • 1,968
  • 1
  • 8
  • 13
1

I think that what are you looking for can be achieved by implementing tabBarController(_:didSelect:) (by conforming to UITabBarControllerDelegate).

It should be similar to (Swift 3):

class ViewController: UIViewController, UITabBarControllerDelegate {
    //...

    override func viewDidLoad() {
        super.viewDidLoad()

        // don't forget to:
        tabBarController?.delegate = self
    }

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        // here, you can determine what's the selected view controller by checking "viewController":
        if viewController is ViewController {
            // the current selected view controller is "ViewController"
        }
    }

    //...
}
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • thanks for answer, one thing here that by selecting a tab I already know which UIViewController I will receive, so actually. But by tapping a tab I want to configure which view controller I want to display for example in tab number 1. – Matrosov Oleksandr Apr 24 '17 at 12:15
  • so it should be kind of re set of tab. If I have VC 1 and VC 2, so based on condition (if block) I will need to have VC 1 in first tab or VC 2 in first tab – Matrosov Oleksandr Apr 24 '17 at 12:16
  • Glad to help :) Oh, I see... for this case, you will need to create your own custom `UITabBarController` and add view controllers to it based in the desired ordering. I hope [this question/answer](http://stackoverflow.com/questions/26850411/how-add-tabs-programmatically-in-uitabbarcontroller-with-swift) might be helpful to your case. – Ahmad F Apr 24 '17 at 12:22
1

Create a tabbar controller class assign that class to your tabbar and override the method

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
   // your code 
}
harshal jadhav
  • 5,456
  • 2
  • 18
  • 26