我正在尝试以编程方式更改我的应用程序中标签栏项目的名称。
在我的 Storyboard 我有一个 UITabBarController 设置为初始 View ,层次结构如下:
UITabBarController -> UINavigationController -> UITableViewController -> Detail View Controller
要更改栏项的标题,您需要更改 UINavigationController 的栏项标题。在 IB 中一切正常,但我需要本地化我的应用程序,这是我动态执行的(无需重新启动应用程序),并且每次启动应用程序时,IB 中给出的标题都已设置,标题不会更改为它们的本地化标题,直到我点击栏项目。
在我各自的 UITableViewControllers 中,我用 self.title = localized title;
设置了标题,效果很好。 但我想让应用程序在启动时更改栏项标题,直到我点击它们。
我已经查看了关于此问题的 SO 上的帖子并尝试了这些建议,但栏项的标题仍然始终设置为来自 IB 的值。我也在下面尝试了这段代码,但这仅在启动时设置了选定的栏项目:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Select the desired tab of our initial tab bar controller:
UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController;
tabBar.selectedIndex = 1;
tabBar.navigationController.title = @"Item 2";
[(UITabBarItem*)[self->tabBarController.tabBar.items objectAtIndex:1] setTitle:@"Item 2"];
// Override point for customization after application launch.
return YES;
}
最佳答案
好的,所以我正在回答我自己的问题。在网上搜索了很长时间,SO,并尝试了各种组合后,我破解了它。下面的帖子帮助我走上了正轨,但它没有解决它(仍然给它+1):
Tab Bar Item title before appear Storyboard
在 UITableViewController .m 文件中,您需要添加此代码以在加载或点击之前设置选项卡栏项的标题。
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (self) {
self.navigationController.tabBarItem.title = NSLocalizedStringFromTableInBundle(@"TITLE_TABLANGUAGE", nil, currentLanguageBundle, @"");
}
return self;
}
答案在于 UITabBarController 的栏项从 UINavigationController 的栏项的标题中获取它们的值,在本例中为标题。在 initWithCoder 方法中设置该标题很重要。将它放在其他位置不会在点击之前设置标题。
关于UITabbarController 以编程方式更改栏项标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23054987/