以编程方式设置标签栏项目

set tab bar items programmatically

我有一个标签栏,我想根据用户的设置更改其项目。所以我需要能够以编程方式 add/remove 选项卡栏中的项目。这是我的代码:

class TabBarViewController: UITabBarController {
var controllerArray = [UIViewController]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    self.tabBar.tintColor = UIColor.greenColor()

    let storyBoard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
    let controller1 = storyBoard.instantiateViewControllerWithIdentifier("Navigation2") as! nav2
    let controller2 = storyBoard.instantiateViewControllerWithIdentifier("Explore") as! ExploreNavigation
    let controller3 = storyBoard.instantiateViewControllerWithIdentifier("friends") as! ExploreNav
    let controller4 = storyBoard.instantiateViewControllerWithIdentifier("controller3ID") as! controller3VC
    controllerArray.append(controller1)
    controllerArray.append(controller2)
    controllerArray.append(controller3)
    controllerArray.append(controller4)
   self.tabBarController?.setViewControllers(controllerArray, animated: true)

  }


}

但是如果我注释掉其中一行,例如像这样:

     //controllerArray.append(controller2)

因此该控制器不属于 controllersArray,控制器仍显示在选项卡栏中。我做错了什么?

这个我也试过了,也没用:

 self.tabBarController?.viewControllers = controllerArray

就说

self.setViewControllers(controllerArray, animated: true)

而不是

self.tabBarController?.setViewControllers(controllerArray, animated: true)

您继承了 UITabBarController 而不是 UIViewController,因此您没有,或者至少不需要 属性 tabBarController。