如何从UIViewController扩展的任何类中以编程方式创建选项卡:
class DashboardTabBarController: UITabBarController { override func viewDidLoad() { //here } ... }
更新SWIFT 3
原文链接:https://www.f2er.com/swift/319834.html以编程方式创建UITabBarController的一个例子可能是这样的:
首先我们创建一个UIViewControllers,它将是标签栏界面的每个选项卡的内容.对于这个例子,我们只创建一个很简单.
class Item1ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.green self.title = "item1" print("item 1 loaded") } }
现在,UITabBarController:
我们创建我们要在标签栏中显示的UIViewControllers的新实例.然后我们为每个我们创建的实例创建一个图标,然后我们创建一个数组,其中包含所有UIViewControllers,它们为选项卡栏界面的每个选项卡指定内容.数组中视图控制器的顺序对应于选项卡栏中的显示顺序.
class DashboardTabBarController: UITabBarController,UITabBarControllerDelegate { override func viewDidLoad() { super.viewDidLoad() delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let item1 = Item1ViewController() let icon1 = UITabBarItem(title: "Title",image: UIImage(named: "someImage.png"),selectedImage: UIImage(named: "otherImage.png")) item1.tabBarItem = icon1 let controllers = [item1] //array of the root view controllers displayed by the tab bar interface self.viewControllers = controllers } //Delegate methods func tabBarController(_ tabBarController: UITabBarController,shouldSelect viewController: UIViewController) -> Bool { print("Should select viewController: \(viewController.title) ?") return true; } }