Подтвердить что ты не робот

Изменение цвета текста уитаббаритем

Есть ли способ изменить цвет uitabbar элемента uitabbar с серого по умолчанию на белый, а выбранный цвет на синий?

4b9b3361

Ответ 1

Старый вопрос, но у меня есть новый ответ, который поддерживается в iOS 5 и далее (также я использую литералы LLVM 4.0)

[[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }
                                         forState:UIControlStateNormal];
[[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor blueColor] }
                                         forState:UIControlStateSelected];

Ответ 2

UITextAttributeTextColor устарел от iOS 7. Вместо этого используйте NSForegroundColorAttributeName.

[[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor blackColor] }
                                             forState:UIControlStateNormal];

И в Swift

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.blackColor()], forState: .Normal)

Ответ 3

EDIT: больше не лучшая практика, поскольку новые API были добавлены в SDK iOS

Подкласс UITabBarController (как CustomTabBarController в этом примере) и поместите следующий код в ваш файл реализации .m:

@interface CustomTabBarController()

@property (nonatomic, retain) NSArray *tabTitleLabels;

@end


@implementation CustomTabBarController

@synthesize tabTitleLabels;

- (NSArray *)tabTitleLabels
{
    // Check if we need to update the tab labels 
    if ([tabTitleLabels count] != [self.viewControllers count])
        self.tabTitleLabels = nil;

    // Create custom tab bar title labels
    if (!tabTitleLabels)
    {
        tabTitleLabels = [[NSMutableArray alloc] init];

        for (UIView *view in self.tabBar.subviews)
        {      
            if ([NSStringFromClass([view class]) isEqualToString:@"UITabBarButton"])
            {
                for (UIView *subview in view.subviews)
                {                                    
                    if ([subview isKindOfClass:[UILabel class]])
                    {
                        UILabel *label = (UILabel *)subview;

                        UILabel *newLabel = [[UILabel alloc] init];
                        newLabel.font = label.font;
                        newLabel.text = label.text;
                        newLabel.backgroundColor = label.backgroundColor;
                        newLabel.opaque = YES;
                        newLabel.frame = CGRectMake(0, 0, label.frame.size.width, label.frame.size.height -1);    
                        [subview addSubview:newLabel];

                        [((NSMutableArray *)tabTitleLabels) addObject:newLabel];
                        [newLabel release];
                    }
                }
            }
        }      
    }

    return tabTitleLabels;
}

// Customize the desired colors here
- (void)recolorTabBarTitleLabels
{
    for (UILabel *label in self.tabTitleLabels)
    {
        label.textColor = [UIColor whiteColor];
        label.backgroundColor = [UIColor blackColor];
    }
    UILabel *selectedLabel = [self.tabTitleLabels objectAtIndex:self.selectedIndex];
    selectedLabel.textColor = [UIColor blueColor];            
    selectedLabel.backgroundColor = [UIColor colorWithWhite:.15 alpha:1];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self recolorTabBarTitleLabels];
}

- (void)tabBarController:(UITabBarController *)theTabBarController didSelectViewController:(UIViewController *)viewController 
{   
    [self recolorTabBarTitleLabels];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.tabTitleLabels = nil;
}

- (void)dealloc
{
    [tabTitleLabels release];
    [super dealloc];
}

@end

Это может быть год спустя, но я надеюсь, что мой код сэкономит кому-то работу!

Примечание. Он не предназначен для поддержки включения/выключения новых элементов панели вкладок, хотя для этого нужно просто reset tabTitleLabels, чтобы сделать это.

Ответ 4

Это может помочь вам

 UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.whiteColor()], forState: .Selected)

Ответ 5

UITabBarItem практически не настраивается, поэтому, если вам нужно, вы можете:

  • Погрузите, выполнив итерацию через subviews UITabBar s, найдите метки с помощью -[NSObject isKindOfClass:] и измените их цвет.

  • Создайте собственные UITabBar и скопируйте элементы табуляции.

  • Попробуйте альтернативы, такие как Three20s TTTabBar.

Ответ 6

Чтобы установить цвет для 2 UIControlState сразу, вы можете использовать union:

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.redColor()], forState: UIControlState.Selected.union(UIControlState.Highlighted))

Ответ 7

Отправляйте этот вопрос и этот вопрос, но имейте в виду, что ваше приложение может быть отклонено для изменяя компоненты табло по умолчанию.

Ответ 8

Swift3

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.brown], for: .normal) 

Ответ 9

Будь проще!

[[UITabBar appearance] setTintColor:[UIColor blackColor]];

Ответ 10

С прошивкой 10 можно установить unselectedItemTintColor на UITabBar.

tintColor UITabBar - это цвет для выбранного UITabBar.

Если вы хотите перейти к уникальным значениям для любого элемента, вы также можете установить tabBarItem.titleTextAttributes(for:) (упоминалось ранее) также для элемента непосредственно в сочетании с tabBarItem.image и tabBarItem.selectedImage.