LoginSignup
3
3

More than 5 years have passed since last update.

Passing data between view controllers from a UITabBarController stack using Swift

Posted at

Let us have two UIViewController classes named viewController1 and viewController2 in our UITabBarController stack and have them as VC1 and VC2 respectively

var VC1: viewController1 = viewController1.alloc()
var VC2: viewController2 = viewController2.alloc()

Let us also have a UITabBarController class named TabBarController and name them tBc

var tBc: TabBarController = TabBarController.alloc()

Then let us contain them in that UITabBarController

tBc.viewControllers = [VC1,VC2]

That is what we need for our Application delegate or something that will initialise our TabBarController

Assuming we have a UILabel named "myLabel" on VC2, let us say we wish to pass data from VC1 to the UILabel on VC2. We would then have this on VC1 to do it:

var vcArray = self.tabBarController?.viewControllers as NSArray!

This would fetch the view controllers in the tabbarcontroller's stack and list them in an array. Then make next UIViewController known on VC1 and name it nextVC:

       var VC2: UIViewController = vcArray.objectAtIndex(1) as UIViewController
       var nextVC = VC2 as viewController2

Then you could now pass data on the next viewcontroller like having this on VC1:

       nextVC.myLabel.text = "This will appear on the next view"
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3