更改未选中标签栏项目的颜色

时间:2014-05-26 17:41:42

标签: ios objective-c uitabbarcontroller uitabbar uitabbaritem

我有一个标签栏控制器,我设法将选定的标签图像和标题设为黑色,未选择的项目标题为白色,但我无法将未选择的项目图像设为白色。

在我的标签栏控制器中: - (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIColor *customColor = [UIColor colorWithRed:179.0/255.0f green:155.0/255.0f blue:107.0/255.0f alpha:1];

    [self.tabBar setBarTintColor:customColor];

    [self.tabBar setSelectedImageTintColor:[UIColor blackColor]];

    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor blackColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];

    UITabBarItem *item0 = [self.tabBar.items objectAtIndex:0];
    UITabBarItem *item1 = [self.tabBar.items objectAtIndex:1];
    UITabBarItem *item2 = [self.tabBar.items objectAtIndex:2];

    item0.image = [[UIImage imageNamed:@"home_unselected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    item0.selectedImage = [UIImage imageNamed:@"home_tab"];
    item1.image = [[UIImage imageNamed:@"contact_unselected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    item1.selectedImage = [UIImage imageNamed:@"contact_tab"];
    item2.image = [[UIImage imageNamed:@"about_unselected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    item2.selectedImage = [UIImage imageNamed:@"about_tab"];
}

enter image description here

1 个答案:

答案 0 :(得分:1)

我得到了这样的工作:

标签栏控制器:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    UIColor *customColor = [UIColor colorWithRed:179.0/255.0f green:155.0/255.0f blue:107.0/255.0f alpha:1];

    [self.tabBar setBarTintColor:customColor];
    [self.tabBar setTintColor:[UIColor blackColor]];

    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor blackColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];
    [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
}

在标签栏上的三个视图控制器中的每一个中:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        self.title = NSLocalizedString(@"Home", @"Home");
        self.tabBarItem.image = [[UIImage imageNamed:@"home_unselected"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.tabBarItem.selectedImage = [UIImage imageNamed:@"home_tab"];
    }
    return self;
}