I am developing an iOS application where the entry point is a login Screen. Which then after the login, segue to a tab bar controller. Now I want to dynamically populate the num
Swift 4 - Xcode 9
You can dynamically change the array of UIViewControllers used by tabBarController at runtime by using:
self.viewControllers = arrayOfUIViewControllers
In your specific case, have 2 arrays of UIViewControllers available and when the tabBarController loads (presumably after login), present an array for level 1 or present another array for level 2 depending on the login data.
To address a more broad question, it might also be helpful to demonstrate another case where the user can generate and remove tabs dynamically at runtime.
The tab names will be coming from Tabs.swift which is my placeholder for CoreData where tab data is stored.
class Tabs: NSObject {
let tabs: [String] = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
}
ViewController.swift does pretty much everything.
import UIKit
class ViewController: UIViewController {
let tabs = Tabs().tabs
var array: [UIViewController] = []
@IBAction func makeNewTab(_ sender: Any) {
let newViewController: UIViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "NewTab") as UIViewController
array = (self.tabBarController?.viewControllers)!
if array.count < tabs.count {
newViewController.title = tabs[array.count]
array.append(newViewController)
self.tabBarController?.setViewControllers(array, animated: true)
}
}
@IBAction func removeTab(_ sender: Any) {
array = (self.tabBarController?.viewControllers)!
if array.count > 1 {
let index = array.index(of: self)
array.remove(at: index!)
self.tabBarController?.setViewControllers(array, animated: true)
}
}
}
So here you instantiate the list of tab names and an empty array of ViewControlers. @IBAction makeNewTab is linked the Add button and @IBAction removeTab is linked to the storyboard Remove button. The buttons won't work if there are less than 2 tabs or if you've run out of tab names.
I've chosen to include this example in my answer because I've been looking for it and finally put one together so maybe others will find it useful as it is related to the broad question headline.