【问题标题】:Programmatically change tabBar item?以编程方式更改 tabBar 项目?
【发布时间】:2016-03-30 10:33:15
【问题描述】:

我想在用户是否登录时更改TabBar Item

例如:我有 5 个不同的 tabBar 项目,都创建了一个 Storyboard。

现在,当我的用户没有帐户时,我想更改索引为 2(或标记 == 2)的 tarBar。我想加载一个不同的 rootViewController。 rootViewController 还不是我的 TabBar 的一个项目,我会加载一个完全不同的控制器。

最好的方法是什么?我可以简单地更改图标:

self.tabBar.items![0].selectedImage = UIImage(named: "icon_cal_grey")

但是如何更改 rootViewController?

我应该在这里做吗?

override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {

    if item.tag == 1 {
        // ?
    }

}

或者不应该创建一个 UINavigationController 作为 RootViewController,并在此处加载“正确”的 ViewController 作为 RootViewController?

【问题讨论】:

    标签: ios swift uitabbar


    【解决方案1】:

    您需要用新的视图控制器替换与 视图控制器 关联的第二个标签。这是示例代码,可能会对您有所帮助:

    NSMutableArray *viewControllers = [[NSMutableArray alloc] initWithArray:self.tabBarController.viewControllers];
    UIViewController *newVC = [UIViewController new];
    UINavigationController *newNav = [[UINavigationController alloc] initWithRootViewController:newVC];
    [viewControllers replaceObjectAtIndex:1 withObject:newNav];
    self.tabBarController.viewControllers = viewControllers 
    

    【讨论】:

    • 谢谢 - 但 replaceObjectAtIndex 在 Swift 中不可用。只有一个“replaceRange”——你知道怎么用吗?
    • @derdida:我使用的是 xcode 7.2,我发现了这个方法 .. let array:NSMutableArray = NSMutableArray() array.replaceObjectAtIndex(1, withObject: Your_object)
    【解决方案2】:

    检查用户是否登录,然后更改UITabBarController的视图控制器:

    tabbarController.viewControllers?.replaceRange()
    

    这也可能有助于Set view controllers of UITabBarController in Swift

    【讨论】:

      【解决方案3】:

      试试这个:

      self.tabBar.selectedIndex = 0
      

      如果你想改变 viewController

      【讨论】:

      • 不,我不想只更改 ViewController,我想更改 RootViewController(还不是 UITabBarItem)
      【解决方案4】:

      下面是 Swift 的代码

              let tabViewCntrls : NSMutableArray = ((self.tabBarController?.viewControllers)! as NSArray).mutableCopy() as! NSMutableArray
      
              let vcLogin = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "LoginScreen") as! LoginScreen
      
              let navRootVC = UINavigationController.init(rootViewController: vcLogin)
      
              navRootVC.viewControllers = [vcLogin]
      
              tabViewCntrls.replaceObject(at: 1, with: navRootVC)
      
              self.tabBarController?.viewControllers = tabViewCntrls as? [UIViewController]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        • 2012-04-06
        • 2017-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多