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

Как изменить неактивный значок/текст на панели вкладок?

Как я могу изменить неактивный значок/цвет текста на панели вкладок iOS 7? Серый цвет.

enter image description here

4b9b3361

Ответ 1

В каждом первом ViewController для каждого TabBar:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // changing the unselected image color, you should change the selected image 
    // color if you want them to be different
    self.tabBarItem.selectedImage = [[UIImage imageNamed:@"yourImage_selectedImage"]
    imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    self.tabBarItem.image = [[UIImage imageNamed:@"yourImage_image"] 
    imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

Ключ этого кода: 'UIImageRenderingModeAlwaysOriginal':

Режимы рендеринга по документации Apple:

UIImageRenderingModeAutomatic,          // Use the default rendering mode for the context where the image is used    
UIImageRenderingModeAlwaysOriginal,     // Always draw the original image, without treating it as a template
UIImageRenderingModeAlwaysTemplate,     // Always draw the image as a template image, ignoring its color information

Чтобы изменить цвет текста:

В AppDelegate:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Add this if you only want to change Selected Image color 
    // and/or selected image text
    [[UITabBar appearance] setTintColor:[UIColor redColor]];

    // Add this code to change StateNormal text Color,
    [UITabBarItem.appearance setTitleTextAttributes:
    @{NSForegroundColorAttributeName : [UIColor greenColor]} 
    forState:UIControlStateNormal];

    // then if StateSelected should be different, you should add this code
    [UITabBarItem.appearance setTitleTextAttributes:
    @{NSForegroundColorAttributeName : [UIColor purpleColor]} 
    forState:UIControlStateSelected];

    return YES;
}

Ответ 2

Вы также можете установить свойство Render As ваших изображений на панели вкладок непосредственно в своем каталоге активов. Там вы можете установить свойство Default, Original Image и Template Image.

Set render option of image

Ответ 3

для изменения цвета значков unselect на вкладке

Для ниже iOS 10:

// this code need to be placed on home page of tabbar    
for(UITabBarItem *item in self.tabBarController.tabBar.items) {
    item.image = [item.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

Над iOS 10:

// this need to be in appdelegate didFinishLaunchingWithOptions
[[UITabBar appearance] setUnselectedItemTintColor:[UIColor blackColor]];

Ответ 4

Вместо добавления этого в каждый UIViewController вы можете создать расширение и изменить внешний вид UITabBarController

Изменить цвет невыделенного значка

extension UITabBarController {
    override public func viewDidLoad() {
        super.viewDidLoad()

        tabBar.items?.forEach({ (item) -> () in
           item.image = item.selectedImage?.imageWithColor(UIColor.redColor()).imageWithRenderingMode(.AlwaysOriginal)
        })
    }
}

Изменить выбранный цвет значка

let tabBarAppearance = UITabBar.appearance()
tabBarAppearance.tintColor = UIColor.blackColor()

Изменить (un) цвет выбранного заголовка

let tabBarItemApperance = UITabBarItem.appearance()
tabBarItemApperance.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Edmondsans-Bold", size: 10)!, NSForegroundColorAttributeName:UIColor.redColor()], forState: UIControlState.Normal)
tabBarItemApperance.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Edmondsans-Bold", size: 10)!, NSForegroundColorAttributeName:UIColor.blackColor()], forState: UIControlState.Selected)

Расширение UIImage

extension UIImage {
    func imageWithColor(color1: UIColor) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        color1.setFill()

        let context = UIGraphicsGetCurrentContext()
        CGContextTranslateCTM(context!, 0, self.size.height)
        CGContextScaleCTM(context!, 1.0, -1.0);
        CGContextSetBlendMode(context!, .Normal)

        let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
        CGContextClipToMask(context!, rect, self.CGImage!)
        CGContextFillRect(context!, rect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage
        UIGraphicsEndImageContext()

        return newImage
    }
}

Ответ 5

Существует лучший способ без использования каждого ViewController только с помощью appdelegate.m

В вашей функции AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions попробуйте это.

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

// repeat for every tab, but increment the index each time
UITabBarItem *firstTab = [tabBar.items objectAtIndex:0];

// also repeat for every tab
firstTab.image = [[UIImage imageNamed:@"someImage.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
firstTab.selectedImage = [[UIImage imageNamed:@"someImageSelected.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

Ответ 6

Чтобы изменить цвет выделения вкладки вместо синего цвета:

  • Выберите tabItem.
  • От "Показать инспектора удостоверений" в правом меню.
  • Установите атрибут "tintColor" с вашим цветом.

введите описание изображения здесь

Ответ 7

Новый ответ для программного программирования с iOS 10+ с Swift 3 заключается в использовании API unselectedItemTintColor. Например, если вы инициализировали свой контроллер панели вкладок внутри вашего AppDelegate, он выглядел бы следующим образом:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        ...

        let firstViewController = VC1()
        let secondViewController = VC2()
        let thirdViewController = VC3()


        let tabBarCtrl = UITabBarController()
        tabBarCtrl.viewControllers = [firstViewController, secondViewController, thirdViewController]

        // set the color of the active tab
        tabBarCtrl.tabBar.tintColor = UIColor.white

        // set the color of the inactive tabs
        tabBarCtrl.tabBar.unselectedItemTintColor = UIColor.gray

        // set the text color

        ...
    }

И для установки выбранных и невыбранных цветов текста:

let unselectedItem = [NSForegroundColorAttributeName: UIColor.green]
let selectedItem = [NSForegroundColorAttributeName: UIColor.red]

self.tabBarItem.setTitleTextAttributes(unselectedItem, for: .normal)
self.tabBarItem.setTitleTextAttributes(selectedItem, for: .selected)

Ответ 8

В Swift 3.0 вы можете записать его следующим образом

Для невыделенного изображения панели вкладок

viewController.tabBarItem.image = UIImage(named: "image")?.withRenderingMode(.alwaysOriginal)

Для выбранного изображения панели вкладок

viewController.tabBarItem.selectedImage = UIImage(named: "image")?.withRenderingMode(.alwaysOriginal)

Ответ 9

Вместо добавления кода изображения рендеринга в каждый viewController для tabBarItem используйте расширение

extension UITabBar{
     func inActiveTintColor() {
        if let items = items{
            for item in items{
                item.image =  item.image?.withRenderingMode(.alwaysOriginal)
                item.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.green], for: .normal)
                item.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.white], for: .selected)
            }
        }
    }
}

Затем вызовите это в свой класс UITabBarController, например

class CustomTabBarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        tabBar.inActiveTintColor()
    }
}

Вы получите вывод, например: введите описание изображения здесь ПРИМЕЧАНИЕ. Не забывайте назначать класс CustomTabBarViewController для своего TabBarController в раскадровке.

Ответ 10

Я думаю, что ответ на @anka довольно хорош, и я также добавил следующий код, чтобы включить цвет оттенка для выделенных элементов:

    let image = UIImage(named:"tab-account")!.imageWithRenderingMode(.AlwaysTemplate)
    let item = tabBar.items![IC.const.tab_account] as! UITabBarItem
    item.selectedImage = image

Или в одной строке:

    (tabBar.items![IC.const.tab_account] as! UITabBarItem).selectedImage = UIImage(named:"tab-account")!.imageWithRenderingMode(.AlwaysTemplate)

Так выглядит:

tabbar

Ответ 11

Вам нужно только поставить этот код в свой первый ViewController, вызываемый для TabBarViewController (ViewDidload):

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

-(void) loadIconsTabBar{
        UITabBar *tabBar = self.tabBarController.tabBar;
        //
        UITabBarItem *firstTab = [tabBar.items objectAtIndex:0];
        UITabBarItem *secondTab = [tabBar.items objectAtIndex:1];
        firstTab.image = [[UIImage imageNamed:@"icono1.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
        firstTab.selectedImage = [[UIImage imageNamed:@"icono1.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        secondTab.image = [[UIImage imageNamed:@"icono2.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ];
        secondTab.selectedImage = [[UIImage imageNamed:@"icono2.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    }

Ответ 12

Вам нужно всего лишь ввести этот код в свой appDelegate.m(didFinishLaunchingWithOptions):

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


[UITabBarItem.appearance setTitleTextAttributes:
@{NSForegroundColorAttributeName : [UIColor orangeColor]}
                                       forState:UIControlStateSelected];

[[UITabBar appearance] setTintColor:[UIColor whiteColor]]; // for unselected items that are gray
[[UITabBar appearance] setUnselectedItemTintColor:[UIColor whiteColor]]; 

Ответ 13

Если вы ищете решение для iOS 11 swift 4, сделайте что-то подобное в app Delegate. Это меняет все невыбранные на черный.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UITabBar.appearance().unselectedItemTintColor = UIColor(displayP3Red: 0, green: 0, blue: 0, alpha: 1)

    return true
}

Ответ 14

Лучший способ изменить цвет элемента "Выбранная вкладка" - добавить один код в метод appdelegate didFinishLaunchingWithOptions

UITabBar.appearance().tintColor = UIColor(red: 242/255.0, green: 32/255.0, blue: 80/255.0, alpha: 1.0)

Он изменит цвет текста выбранного элемента

Ответ 16

для быстрого 3:

    // both have to declare in view hierarchy method
    //(i.e: viewdidload, viewwillappear) according to your need.

    //this one is, when tab bar is selected
    self.tabBarItem.selectedImage = UIImage.init(named: "iOS")?.withRenderingMode(.alwaysOriginal)

    // this one is when tab bar is not selected
    self.tabBarItem.image = UIImage.init(named: "otp")?.withRenderingMode(.alwaysOriginal)

Ответ 17

Я думаю, что пришло время использовать

UITabBar unselectedItemTintColor внешний вид

/// Unselected items in this tab bar will be tinted with this color. Setting this value to nil indicates that UITabBar should use its default value instead.
    @available(iOS 10.0, *)
    @NSCopying open var unselectedItemTintColor: UIColor?

Просто добавьте эту строку в приложение завершил запуск

UITabBar.appearance().unselectedItemTintColor = {your color}
// Example
UITabBar.appearance().unselectedItemTintColor = .black

Tab Bar unselectedItemTintColor appearance

Ответ 18

это сработало для меня SWIFT 3

viewConroller.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "image")?.withRenderingMode(.alwaysOriginal),
                                selectedImage:  UIImage(named: "image"))

Ответ 19

Быстрое решение: для элемента UNSELECED: в каждом ViewController → ViewDidLoad()

self.tabBarItem = UITabBarItem(title: nil, image: UIImage(named: "PHOTO_NAME")?.imageWithRenderingMode(.AlwaysOriginal), selectedImage: UIImage(named: "NAME"))