如何动态更改UITabBarItem的标题

时间:2018-11-07 13:10:12

标签: swift uitabbarcontroller uitabbaritem

我的应用程序中有一个 TabBarController ,并且第二项的标题应为LoginProfile,具体取决于用户是否登录。

TabBarController 中:

import UIKit

class TabNavigationBarVC: UITabBarController, UITabBarControllerDelegate {

    override func viewDidLoad() {
        self.delegate = self
        if UserDefaults.standard.bool(forKey: "isUserLoggedIn") {
            tabBar.items?[1].title = "Prof"
            tabBar.items?[1].image = UIImage(named: "user_male")

        } else {
            tabBar.items?[1].title = "Log"
            tabBar.items?[1].image = UIImage(named: "user_male")          
        }        
    }
}

和第二个 TabBarItem RouterVC 连接:

import UIKit
class RouterViewController: UINavigationController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let profile = storyboard?.instantiateViewController(withIdentifier: "ComponentUserProfile") as? UserProfileViewController
        let login = storyboard?.instantiateViewController(withIdentifier: "ComponentLogin")  as? LoginViewController
        if UserDefaults.standard.bool(forKey: "isUserLoggedIn") {
        //profile?.tabBarItem.title = "prr" - no effect
        //profile?.tabBarItem = UITabBarItem(title: "PROFILE", image: UIImage(named: "user_male"), tag: 0) - no effect
            viewControllers = [profile] as! [UIViewController]
       } else {
        //login?.tabBarItem.title = "logg"- no effect
        //login?.tabBarItem = UITabBarItem(title: "LOGIN", image: UIImage(named: "user_male"), tag: 0)- no effect
            viewControllers = [login] as! [UIViewController]
       }
    }
}

所有功能均正常运行,但仅在用户启动应用程序时有效。稍后,在用户注销后,我希望tabBar中的第二个标题从Profile更改为login,或者-当用户成功登录时-从Login更改为Profile。我在RouterVC中尝试了类似注释的代码行,但是没有任何变化。

LoginVC 中,此行也无法正常工作:

override func viewWillAppear(_ animated: Bool) {
        self.tabBarItem.title = "loggggg"
    }

如何动态进行此更改?

也许我应该为TabBarController写扩展名,以跟踪UserDefaults.standard.bool(forKey: "isUserLoggedIn")是否已更改并显示tabbarItem的正确标题?。

p.s。在视图之间导航,登录/注销效果很好,该点仅在标题中

p.p.s-找到答案,如何从视图访问标题-添加self.tabBarController?.tabBar.items?[1].title = "profile",但仍在寻找一些常见的决定,例如跟踪UserDefaults键。.

1 个答案:

答案 0 :(得分:0)

您可以使用来更新所选的商品标题

self.tabBarController?.tabBar.selectedItem?.title = "demo"