Nauman Zafar
Nauman Zafar

Reputation: 1103

Accessing child view controllers of a UITabBarController

I am new to iOS, How can I access child view controllers form UITabBarController ? Currently, I have the following.

  1. RequestTabBarController
  2. ActiveRequestsTableViewController
  3. RequestViewController

The child view controllers are connected using a Relationship Segue in the storyboard. I want to set some properties in child views from UITabBarController. How this can be accomplished.

Storyboard

storyboard_reference

Upvotes: 1

Views: 3677

Answers (4)

mugx
mugx

Reputation: 10105

You might define the following enum for mapping your classes:

enum TabType:Int {
    case RequestTabBarController
    case ActiveRequestsTableViewController
    case RequestViewController
}

In such way you can have a clean access to your viewControllers:

An array of the root view controllers displayed by the tab bar interface.

which you can get directly from your UITabBarController, doing so:

private weak var tabVc:UITabBarController?
var niceObject:Whatever?
//...//
override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    self.tabVc = segue.destination as? UITabBarController

    if let vc = self.tabVc?.viewControllers?[TabType.RequestTabBarController.rawValue] as? RequestTabBarController {
        vc.doWhatEver(niceObject)
    }
}

Upvotes: 4

André Slotta
André Slotta

Reputation: 14030

If you setup your UI in storyboard you can implement prepareForSegue in your UITabBarController subclass. It gets called once for every childViewController. To distinguish between the different childViewControllers you can either use segueIdentifiers or check the segues' destinationViewControllers type (assuming each childViewController has a different type).

Upvotes: 0

Harish
Harish

Reputation: 368

From your description above I understand you want to access the children of TabController in order to change some of their properties. If my understanding is correct then you can use the viewcontrollers property of UITabBarController to access the children and set the properties.

Upvotes: 1

Arnab
Arnab

Reputation: 4356

Create a subclass of UITabBarController (for your case it is probably ManageRequestTabBarController) and there implement the UITabBarControllerDelegate:

public func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController)

This delegate is called when you tap on any tab item and before going to the viewController which is connected with that tabItem.

Here viewController is the destination viewController. Use it like this:

if viewController is YourDestinationVC {
    let yourDestinationVC = viewController as! YourDestinationVC
    yourDestinationVC.yourCustomValue = someValueYouWantToPass
}

Upvotes: 0

Related Questions