Как изменить цвет текста элемента панели вкладок - программирование
Подтвердить что ты не робот

Как изменить цвет текста элемента панели вкладок

enter image description here

Как изменить цвет текста "Дополнительно.." на вкладке, чтобы он соответствовал цвету значка. (Прямо сейчас Производительность выбрана на панели вкладок)

Я попытался установить TitleTextAttributes.

[moreItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaLTStd-Roman" size:10.0f], NSFontAttributeName,  [UIColor yellowColor],NSForegroundColorAttributeName , nil]

Но цвет текста всегда установлен на желтый. даже когда элемент выбран. Как это enter image description here

Я пытаюсь установить белый, когда он выбран, и когда он не выбран, он должен совпадать с цветом значка. Благодаря.. Любые предложения будут действительно полезными.

4b9b3361

Ответ 1

Я нашел ответ на свой вопрос.

Мы можем установить perforamceItem setTitleTextAttributes: для двух разных состояний.

  • forState:UIControlStateNormal
  • forState:UIControlStateHighlighted

Я добавил следующий код

 [performanceItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaLTStd-Roman" size:10.0f], NSFontAttributeName,  [UIColor yellowColor], NSForegroundColorAttributeName,nil] forState:UIControlStateNormal];

[performanceItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaLTStd-Roman" size:10.0f], NSFontAttributeName,  [UIColor whiteColor], NSForegroundColorAttributeName,nil] forState:UIControlStateHighlighted];

Мне нужно заменить желтый цвет цветом моих ИКОНОВ. Вот как они сейчас выглядят.

Если выбрано "Больше"

When More is selected

Когда выбрана производительность

When Performance is Selected

Ответ 2

Принятый код ответа не работает для меня.

Вот код, который работает:

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

Ответ 3

Это быстрая версия: -

        for item in self.mainTabBar.items! {

          let unselectedItem: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
          let selectedItem: NSDictionary = [NSForegroundColorAttributeName: UIColor.whiteColor()]
          item.setTitleTextAttributes(unselectedItem as? [String : AnyObject], forState: .Normal)
          item.setTitleTextAttributes(selectedItem as? [String : AnyObject], forState: .Selected)

        }

Или вы можете просто изменить Appdelegate: -

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blueColor()], forState: .Selected)
    UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.blackColor()], forState: .Normal)
    // Override point for customization after application launch.
    return true
}

Ответ 4

Код бесплатный способ сделать это:

Если вы используете iOS 10, вы можете изменить оттенок изображения на панели вкладок.

enter image description here

Если вы также поддерживаете iOS 9 и ниже, вы также должны добавить tintColor к своим пользовательским атрибутам времени выполнения в каждом элементе панели вкладок.

enter image description here

если вы также хотите изменить цвет значка, убедитесь, что в папке с папками находится правильное цветное изображение, и измените "Отрисовка" на "Исходное изображение".

enter image description here

Ответ 5

Свифт 4:

UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.white], for: .normal)
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.red], for: .selected)

Ответ 6

Swift 5.1 + iOS 12.4 & iOS 13:

/// Subclass of 'UITabBarController' that is used to set certain text colors for tab bar items.
class TabBarController: UITabBarController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let items = tabBar.items {
            // Setting the title text color of all tab bar items:
            for item in items {
                item.setTitleTextAttributes([.foregroundColor: UIColor.black], for: .selected)
                item.setTitleTextAttributes([.foregroundColor: UIColor.lightGray], for: .normal)
            }
        }
    }
}

Ответ 7

Для быстрого решения, дайте тип вывода вашему другу:

override func viewWillAppear(animated: Bool) {
  for item in self.tabBar.items! {
    let unselectedItem = [NSForegroundColorAttributeName: UIColor.blackColor()]
    let selectedItem = [NSForegroundColorAttributeName: UIColor.whiteColor()]

    item.setTitleTextAttributes(unselectedItem, forState: .Normal)
    item.setTitleTextAttributes(selectedItem, forState: .Selected)
  }
}

Ответ 8

Быстрая версия ответа @skywinder:

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

Ответ 9

Это простой, простой подкласс UITabBarItem и назначить его классом элемента панели вкладок в раскадровке или коде. Нижеследующее прекрасно работает для меня.

import UIKit

class PPTabBarItem: UITabBarItem {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }
    override init() {
        super.init()
        commonInit()
    }

    func commonInit() {
        self.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13), NSForegroundColorAttributeName:UIColor.blackColor()], forState: UIControlState.Normal)

        self.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13), NSForegroundColorAttributeName:UIColor.yellowColor()], forState: UIControlState.Selected)
    }
}

Решение skywinder хороша, но оно вызывает глобальную область.

Ответ 10

Это работает правильно.

 [[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                        [UIColor redColor], NSForegroundColorAttributeName,
                                                       nil] forState:UIControlStateSelected];

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

Ответ 11

Это сработало для меня на Swift 5.

В AppDelegate:

 UITabBarItem.appearance().setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.red], for: .selected)