Reputation: 811
How to set the tab bar title at Startup or AppDelegates
. I have 5 Tab Bar Item
, 4 of which is embedded in a Navigation Controller
and 1 is without and just a tab bar item
. Please see the following pic
#import "AppDelegate.h"
@interface ProfileChgLang (){
AppDelegate *appDelegate;
NSString *sLanguage;
}
- (IBAction)btnChinese:(id)sender {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"CN" forKey:@"txtLanguage"];
[(AppDelegate*)[UIApplication sharedApplication].delegate setupTabBar];
//UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//==== Is the following correct? =====
UITabBarController * tabBarController = (UITabBarController*)[[[UIApplication sharedApplication] keyWindow] rootViewController];
[self presentViewController:tabBarController animated:YES completion:nil];
}
//====================================
- (void)setupTabBar {
//===Should be this
UITabBarController * tabBarController = (UITabBarController*)[self.window rootViewController];
//===Or this
UITabBarController * tabBarController = (UITabBarController*)[[[UIApplication sharedApplication] keyWindow] rootViewController];
if(tabBarController != nil) {
((UIViewController*)[tabBarController.viewControllers objectAtIndex:1]).tabBarItem.title = @"Your desired Title";
}
Upvotes: 1
Views: 466
Reputation: 20804
Any UIViewController
have this property tabBarItem
because is an extension of UIViewController
so you only have to get your viewController and set his tabBarItem.title
property = "your desiredTitle"
Objective-C Code
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self setupTabBar];
// Override point for customization after application launch.
return YES;
}
- (void)setupTabBar {
UITabBarController * tabBarController = (UITabBarController*)[self.window rootViewController];
if(tabBarController != nil) {
((UIViewController*)[tabBarController.viewControllers objectAtIndex:3]).tabBarItem.title = @"YourDesiredTitle";
}
}
Swift Code
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//Whatever you have here
self.setupTabBar()
return true
}
func setupTabBar() {
if let tabBarController = self.window?.rootViewController as? UITabBarController {
if let navigationsControllers = tabBarController.viewControllers as? [UIViewController] {
navigationsControllers[3].tabBarItem.title = "YourTitle"
}
}
}
if you want to call this method from anywhere in your code you must
Code
[(AppDelegate*)[UIApplication sharedApplication].delegate setupTabBar];
Upvotes: 2