选中时设置TabBar图标色调

时间:2013-08-19 22:04:45

标签: iphone objective-c uitabbaritem

我正在尝试设置UITabBarItem的图标,但它无法正常工作。顺便说一句,我正在为这个项目使用Xcode 5 Beta。

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    {
        [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
        UIImage *tabBarBackground = [UIImage imageNamed:@"tabbar.png"];
        [[UITabBar appearance] setBackgroundImage:tabBarBackground];
        [[UITabBar appearance] setSelectionIndicatorImage:[UIImage imageNamed:@"tabbar_selected.png"]];
        [[UITabBar appearance] setTintColor:[UIColor whiteColor]];
    }
    return YES;
}

enter image description here

我试图在选中和未选中时将图标设为白色,但在未选择状态下它们仍保持灰色。


修改

我尝试过这样做,但现在我得到错误“表达结果未使用”

UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
        UITabBar *tabBar = tabBarController.tabBar;
        UITabBarItem *tabBarItem1 = [tabBar.items objectAtIndex:0];
        tabBarItem1.title = @"Home";
        UIImage *graph = [UIImage imageNamed:@"graph.png"];
        [tabBarItem1 initWithTitle:(NSString *)@"HELLO" image:(UIImage *)graph selectedImage:(UIImage *)graph];

1 个答案:

答案 0 :(得分:0)

tintColor设置背景的色调颜色,如果使用自定义背景图像,则无法看到此颜色。如果您不想使用系统默认渐变,则必须使用setFinishedSelectedImage:withFinishedUnselectedImage:并为它们设置白色图像。

像这样:

UIImage *selectedImage = ...
UIImage *unselectedImage = selectedImage;
[tabBarItem setFinishedSelectedImage:selectedImage withFinishedUnselectedImage:unselectedImage];

如果要在Storyboard中设置这些图像,则可以迭代现有的UITabBarItem并更改其图像。

将这样的内容放入application:didFinishLaunchingWithOptions:

UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
NSAssert([tabBarController isKindOfClass:[UITabBarController class]], @"self.window.rootViewController must be a tabBarController");
for (UIViewController *viewController in tabBarController.viewControllers) {
    UITabBarItem *tabBarItem = viewController.tabBarItem;
    UIImage *tabImage = tabBarItem.image;
    [tabBarItem setFinishedSelectedImage:tabImage withFinishedUnselectedImage:tabImage];
}