如何在tabbarcontroller中运行代码

时间:2013-09-26 16:13:58

标签: objective-c xcode ios7

我试图更改未选中的标签栏图标图像的图标色调。我已经使用了下面的补丁代码,但是,我发现这个补丁代码的帖子说在标签栏控制器中运行它,但我不知道该怎么做,所以我在 - (void)viewDidLoad方法中运行它viewcontroller .m文件。它提出了一个错误,说“在'ViewController *'类型的对象上找不到”属性'tabBar'如何解决这个问题?

// set color of selected icons and text to red
self.tabBar.tintColor = [UIColor redColor];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor redColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];


// set color of unselected text to green
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor greenColor], NSForegroundColorAttributeName, nil]
                                         forState:UIControlStateNormal];

// set selected and unselected icons
UITabBarItem *item0 = [self.tabBar.items objectAtIndex:0];

// this way, the icon gets rendered as it is (thus, it needs to be green in this example)
item0.image = [[UIImage imageNamed:@"unselected-icon.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

// this icon is used for selected tab and it will get tinted as defined in self.tabBar.tintColor
item0.selectedImage = [UIImage imageNamed:@"selected-icon.png"];

2 个答案:

答案 0 :(得分:1)

尝试在VC中执行以下操作,而不是使用该代码补丁:

[self.tabBarItem setFinishedSelectedImage:[UIImage imageNamed:@"item_seleted.png"] withFinishedUnselectedImage:[UIImage imageNamed:@"item_unselected.png"]];

编辑:

上面的代码在子类化UITabBarController时使用,所以如果你需要继承'UITabBarController',那么在故事板中更改tabBarController的类,并将该代码块放在{{1}中}。

答案 1 :(得分:0)

您可以从故事板中删除UIViewController并添加UITabBarController并将其设置为Initial View Controller

然后,您可以像UITabBarController一样访问此AppDelegate.m

UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;

这是快捷方式。

您也可以继承UITabBarController,在故事板中设置此类,并将所有代码放在此子类中。 (因为null在15分钟之前说过:)