Pass data between controllers within a tab bar IOS swift3

0

Hi, I'm starting to program in Swift3 on iOS and I need to do a tab bar but I do not know how I can pass data between the controllers, can someone help me?

    
asked by Daniel ORTIZ 16.03.2017 в 15:35
source

3 answers

1

You have already tried to persist the data in one of the view controllers and then extract them where you need them

Another option is to create a singleton and only query the singleton object

    
answered by 03.04.2017 в 00:29
1

You can use a singleton class that you use from the two controllers or retrieve the controller instance from the tab and put the value to the property you want in this way ....

self.tabBarController? .tabBar.items? [1] where items? is an array of ViewControllers ... and the number corresponds from left to right the place it occupies. Therefore the first screen corresponds to 0 luck

    
answered by 21.11.2017 в 16:35
0

You can declare a property (or several) in UITabBarController , and this will be accessible from each of the children through the existing property in all UIViewControllers open var tabBarController: UITabBarController? { get } (provided that they have a UITabBarController configured as father).

For this you will need to create a subclass of UITabBarController , and assign the corresponding classes in Storyboard .

A demo could be the following:

class MyTabBarController: UITabBarController {

   var myString: String?

   override func viewDidLoad() {
       super.viewDidLoad()

   }
}

class MyChildViewController1: UIViewController {

   var myTabBar: MyTabBarController? {
       return tabBarController as? MyTabBarController
   }

   override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated)

      print("stringValue: \(myTabBar?.myString ?? "nil")")

      myTabBar?.myString = "Value of controller 1"
   }
}


class MyChildViewController2: UIViewController {

   var myTabBar: MyTabBarController? {
       return tabBarController as? MyTabBarController
   }

   override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated)

      print("stringValue: \(myTabBar?.myString ?? "nil")")

      myTabBar?.myString = "Value of controller 1"
   }
}

As you change from tab to another, you will see how the value assigned in the previous controller is printed. (the first print will print nil )

    
answered by 05.04.2017 в 22:16