Swift 4 - 如何重写选项卡栏以打开视图控制器

4

当用户点击选项卡栏目时,我是否可以在 UITabBarController 中覆盖此操作,然后检查 UserDefault ,以决定是显示视图还是保持当前视图不变?

代码示例:

override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    if item.image == UIImage(named: "TabProfile")
    {
        // Profile tab selected
        if !loginController.isUserLogged()
        {
            // Not logged in...
            showLoginView()  

            // Following line doesn't work...
            tabBarController?.selectedIndex = selectedIndex
        }
    }
}

如果可能的话,我希望执行此检查,如果false,则实际上阻止视图甚至到达viewDidLoad
谢谢。

1
在用户登录之前,避免添加选项卡不是更好吗?或者至少在用户登录之前禁用选项卡条目? - rmaddy
@rmaddy 我考虑过这个问题,但我希望用户能够在不创建账户的情况下浏览所有内容。 - Niall Kiddle
你的整个问题是在询问如何有条件地防止用户选择一个选项卡。也许我在评论中放错了条件,但它仍然适用。在满足条件之前不要添加(或只需禁用)该选项卡。 - rmaddy
在这种情况下,访客用户与个人资料选项卡之间的交互会显示登录弹出窗口。这是期望的功能。也许我表达问题不当,没有给足够的上下文。无论如何,谢谢。 - Niall Kiddle
1个回答

2
我猜您需要:

我想你需要

func tabBarController(_ tabBarController: UITabBarController, 
              shouldSelect viewController: UIViewController) -> Bool {
   if let ind = tabBarController.viewControllers!.index(of:viewController) , ind == 2 { // suppose profile is 2
      // 
       if userNotLogged { 
         // present modal login view 
         return false
       } 
   } 
  return true
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接