如何以编程方式创建UITabBar并在标签之间切换?

时间:2016-01-17 07:39:25

标签: ios swift

我有以下代码用于创建UITabBar,但不知道如何为标签添加操作以便在它们之间切换。

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let item1 = UITabBarItem()
        let item2 = UITabBarItem()
        let bar = UITabBarController()
        let view1 = UIViewController()
        let view2 = UIViewController()

        bar.viewControllers = [view1 , view2]
        let tab = bar.tabBar as UITabBar
        item1.title = "Hi"
        item2.title = "bye"
        view.addSubview(tab)
        view1.tabBarItem = item1
        view2.tabBarItem = item2



    }
}

1 个答案:

答案 0 :(得分:1)

由于您的意图似乎是切换视图控制器,您应该使用UITabBarController。然后,通过分配selectedViewController或selectedIndex来切换ViewControllers。阅读更多:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITabBarController_Class/#//apple_ref/occ/instp/UITabBarController/selectedViewController