简体   繁体   中英

iOS: Tab bar item title before the tab is selected

In iOS 9, the view controller that is displayed in a tab is responsible for it's tabBarItem . But a tab bar controller only loads the view controllers for each tab as they are needed. So initially, it only loads the view controller for tab 1 (if the app launches on the first tab). Therefore, unless you're setting the title for each tab item in a storyboard, only the first tab displays a title since it is the only view controller loaded at that time, while the rest only show their icon (which I am doing through a storyboard since the icon doesn't need to be localized).

How can you set the title for all tabs without doing it through a storyboard?

You can put all the titles into array, and preset the tabBarItem title:

if let tabTitles = self.tabBarController?.tabBar.items as? [UITabBarItem]
    {
        tabTitles[0].title = "Messages"
        tabTitles[1].title = "Contacts"
    }

Try Below code hope this help you

// MyTabBarController.h

#import <UIKit/UIKit.h>
@interface MyTabBarController : UITabBarController
@end

// MyTabBarController.m

#import "MyTabBarController.h"
@interface MyTabBarController ()

@end

@implementation MyTabBarController

- (void)viewDidLoad {[super viewDidLoad];
[self customizedTabbar];
}
-(void)customizedTabbar
{
 UITabBar *tabBar = self.tabBar;
UITabBarItem *item0 = [tabBar.items objectAtIndex:0];
UITabBarItem *item1 = [tabBar.items objectAtIndex:1];

UIImage *img1= [[UIImage imageNamed:@"t1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

UIImage * img1_sel= [[UIImage imageNamed:@"t1_sel"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

   UIImage *img2= [[UIImage imageNamed:@"t2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

UIImage *img2_sel= [[UIImage imageNamed:@"t2_sel"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

 item0 = [item0 initWithTitle:@"Tab1" image:img1 selectedImage:img1_sel];

item1 = [item1 initWithTitle:@"Tab2" image:imag2 selectedImage:img2_sel];
 }

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM