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?
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
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
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
)