iOS以编程方式更改标签栏项目图像,无法正常工作

时间:2014-11-26 11:55:23

标签: ios tabbar

尝试以编程方式在标签栏上设置图像时出现问题。

我希望所有标签都带有黑色背景和带有白色文字的白色图标。当您浏览它们时,所选的选项卡会更改,以便它具有带有白色图标和标题的红色背景。现在,我在所有选项卡上都有相同的图像用于测试目的。但他们将是所有不同的图像。

现在我的问题是,似乎忽略了这段代码,并出现了“原始”(带有故事板的设置)。除非在故事板中更改值,否则不会发生任何变化。

我尝试在我的AppDelegate文件中的didFinishLaunchingWithOptions中设置它们:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
UITabBarController *tc = [mainStoryboard instantiateViewControllerWithIdentifier:@"tabbar"];

UITabBar *tabBar = tc.tabBar;
UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
UITabBarItem *tabBarItem2 = [tabBar.items objectAtIndex:1];
UITabBarItem *tabBarItem3 = [tabBar.items objectAtIndex:2];
UITabBarItem *tabBarItem4 = [tabBar.items objectAtIndex:3];
UITabBarItem *tabBarItem5 = [tabBar.items objectAtIndex:4];

tabBarItem1.selectedImage = [[UIImage imageNamed:@"ikon_clubkort"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem1.image = [[UIImage imageNamed:@"ikon_clubkort"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem1.title = @"xxxx";

tabBarItem2.selectedImage = [[UIImage imageNamed:@"ikon_clubkort"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem2.image = [[UIImage imageNamed:@"ikon_clubkort"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem2.title = @"xxxx";

tabBarItem3.selectedImage = [[UIImage imageNamed:@"ikon_clubkort"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem3.image = [[UIImage imageNamed:@"ikon_clubkort"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem3.title = @"xxxx";

tabBarItem4.selectedImage = [[UIImage imageNamed:@"ikon_clubkort"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem4.image = [[UIImage imageNamed:@"ikon_clubkort"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem4.title = @"xxxx";

tabBarItem5.selectedImage = [[UIImage imageNamed:@"ikon_clubkort"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem5.image = [[UIImage imageNamed:@"ikon_clubkort"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
tabBarItem5.title = @"xxxx";

return YES; 
}

知道我做错了吗?

1 个答案:

答案 0 :(得分:2)

根据我的阅读,基本上你是以编程方式创建一个Tab Bar Controller但不显示它。

你可以做两件事:

  1. 将创建的标签栏控制器设置为代理的根视图控制器,方法是将其放在application:didFinishLaunchingWithOptions的末尾:

    self.window.rootViewController = tc

  2. 创建UITabBarController的子类,将您在新课程中设置的标签栏项目设置代码放入' viewDidLoad方法,并将类分配给情节提要中的视图控制器。