I have a TabBarController in my App, and the 2nd item should have title Login
or Profile
depending on whether the user is logged in or not.
in 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")
}
}
}
and 2nd TabBarItem is connected with 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]
}
}
}
all works correctly but only when the user launches the app. Later, after the user has logged out, I would like the 2nd title in the tabBar to change from Profile
to login
, or - when the user is successfully logged in - from Login
to Profile
. I tried something like commented lines of code in RouterVC
, but nothing changed.
And in LoginVC this lines not working too:
override func viewWillAppear(_ animated: Bool) {
self.tabBarItem.title = "loggggg"
}
How can I make this change dynamically?
Maybe I should write extension for TabBarController
to track if UserDefaults.standard.bool(forKey: "isUserLoggedIn")
is changed and display correct title of the tabbarItem
?..
p.s.navigation between views, login/logout works good, the point is only in title
p.p.s - find the answer how get access to the title from view - add self.tabBarController?.tabBar.items?[1].title = "profile"
, but still looking for some common decision, like tracking UserDefaults
key..