UITabbarController以编程方式更改栏项目标题

时间:2014-04-14 08:04:55

标签: uitabbarcontroller tabbar items

我尝试以编程方式更改应用中标签栏项的名称。

在我的 storyboard 中,我将UITabBarController设置为初始视图,层次结构如下:

UITabBarController - > UINavigationController - > UITableViewController - >详细视图控制器

要更改条形图的标题,您需要更改条形项的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;

}

4 个答案:

答案 0 :(得分:6)

好的,我回答了自己的问题。经过相当长的一段时间搜索网络,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方法中设置该标题非常重要。把它放在其他地方之前不会设置标题。

答案 1 :(得分:4)

我认为你使它变得比它需要的更困难。要在运行时更改选项卡栏的标题,只需从维护相关选项卡的viewcontroller中执行以下操作:

self.navigationController.tabBarItem.title = @"desired title text";

进行。

答案 2 :(得分:0)

直接使用此功能:

     private func updateTabBarTitles() {
     if let navControllers = viewControllers as? [UINavigationController] {

         let vcs = navControllers.map({$0.viewControllers.first!})

         for vc in vcs {
             switch vc {
           case is First:    vc.navigationController?.tabBarItem.title = "firstVCTabbarTitle"
           case is Second:    vc.navigationController?.tabBarItem.title = "secondVCTabbarTitle"
           default: break

             }
         }
     }
 }

答案 3 :(得分:0)

在Swift 5和Xcode 11中

一个不错的选择是使用SF符号。从Apple website下载SF符号。 然后打开应用程序,然后选择所需的符号。用CMD-Shift-C复制名称。

在View Controller上使用它

profileViewController.tabBarItem = 
   UITabBarItem(
      title: "Profile", 
      image: UIImage(systemName: "person.fill"),
      tag: 2)
相关问题