在 Swift 中以编程方式隐藏 TabBarViewController 中的选项卡

Hiding tabs in TabBarViewController Programmatically in Swift

我有一个 TabBarViewController,我想 visible/invisible 根据某些条件自动制作一些选项卡。我尝试了以下但没有用。 self.tabBarController?.tabBar.items? return 无。

class MainPageTabBar: UITabBarController, UITabBarControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        if Auth.auth().currentUser != nil {

            if let tabBarItem = self.tabBarController?.tabBar.items?[3] {
                tabBarItem.isEnabled = false
            }
        } else {
            if let tabBarItem = self.tabBarController?.tabBar.items?[4] {
                print("I have tabbb")
                tabBarItem.isEnabled = false
            }
        }

    }
}

将 window 的 rootViewController 设置为你想要的 viewcontroller 像这样:UIApplication.shared.keyWindow?.rootViewController = vc

在你的标签栏上 vc 你需要做的就是

     override func viewDidLoad() {
     super.viewDidLoad()
      tabBarController?.delegate = self
      if userStatus == 1 {      //userStatus is sting where check the user status so if userstatus is 1 then tabbar show 4 tabs otherwise tabbar show 3 tabs

            self.viewControllers![0].title = "DASHBOARD"
            self.viewControllers![1].title = "COMMUNITIES"
            self.viewControllers![2].title = "ADMIN ACCOUNTS"
            self.viewControllers![3].title = "REPORTS"
        }else{
            var viewControllers = self.viewControllers
            viewControllers?.remove(at: 2)  // here i'm removing my no 2 tabs which is ADMIN ACCOUNTS you can see in above conditions and then i'm replacing that 2 index with third index as you see
            self.viewControllers = viewControllers
            self.viewControllers![0].title = "DASHBOARD"
            self.viewControllers![1].title = "COMMUNITIES"
            self.viewControllers![2].title = "REPORTS"
        }
}

此代码还用于标签栏 class。

我正在研究 xcode 11.1,所以它对我来说很好,希望它对你有用。 谢谢