如何快速在 UITabBarController 中以编程方式添加选项卡? [英] How add tabs programmatically in UITabBarController with swift?

查看:24
本文介绍了如何快速在 UITabBarController 中以编程方式添加选项卡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 UIViewController 扩展的任何类以编程方式创建选项卡:

How to create programmatically tabs from any class extended by UIViewController:

class DashboardTabBarController: UITabBarController {

    override func viewDidLoad() {
        //here

    }
 ...

}

推荐答案

UPDATE SWIFT 5

如何以编程方式创建 UITabBarController 的示例如下:

One example of how to create an UITabBarController programmatically could be like this:

首先我们创建UIViewControllers,它将成为标签栏界面每个标签的内容.对于这个例子,我们只创建一个非常简单的.

First we create the UIViewControllers that will be the content for each tab of the tab bar interface. For this example we only create one very simple.

class Item1ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.green
        self.title = "item1"
        print("item 1 loaded")
    }
}

现在,UITabBarController:

我们创建了要在选项卡栏中显示的 UIViewControllers 的新实例.然后我们为我们创建的每个实例创建一个图标,然后我们创建一个包含所有 UIViewControllers 的数组,这些 UIViewControllers 指定了标签栏界面的每个标签的内容.数组中视图控制器的顺序对应标签栏中的显示顺序.

We create the new instances of the UIViewControllers that we want to display in the tab bar. Then we create an icon for each instance we have created and then we create an array that contains all UIViewControllers that specify the content for each tab of the tab bar interface. The order of the view controllers in the array corresponds to the display order in the tab bar.

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;
    }
}

这篇关于如何快速在 UITabBarController 中以编程方式添加选项卡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆