Cómo cambiar el icono inactivo / color de texto en la barra de pestañas?


¿Cómo puedo cambiar el color del icono/texto inactivo en la barra de pestañas de iOS 7? El de color gris.

introduzca la descripción de la imagen aquí

Author: Gabriel.Massana, 2014-03-31

18 answers

En cada primer ViewController para cada 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];
}

La pista de este código es 'UIImageRenderingModeAlwaysOriginal':

Modos de renderizado por Documentación de 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

Para cambiar el color del texto:

En 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;
}
 83
Author: Gabriel.Massana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-31 20:38:44

También puede establecer la propiedad Render As de las imágenes de la barra de pestañas en el catálogo de activos directamente. Allí tiene la opción de establecer la propiedad en Default, Original Image y Template Image.

Establecer la opción de renderizado de la imagen

 112
Author: anka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-30 08:00:41

Para cambiar el color de los iconos de deseleccionar de tabbar

Por debajo de 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];
}

Por encima de iOS 10:

// this need to be in appdelegate didFinishLaunchingWithOptions
[[UITabBar appearance] setUnselectedItemTintColor:[UIColor blackColor]];
 12
Author: Vaibhav Gaikwad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-05 10:26:26

En lugar de agregarlo a cada UIViewController, puede crear una extensión y alterar la apariencia de un UITabBarController

Cambiar el color del icono no seleccionado

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

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

Cambiar el color del icono seleccionado

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

Cambiar (no)el color del título seleccionado

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)

Extensión 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
    }
}
 10
Author: Steve Stomp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-28 00:50:43

Hay una mejor manera sin usar cada ViewController usando solo appdelegate.m

En tu función AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions, prueba esto.

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];
 7
Author: Umitk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-31 08:22:05

Para cambiar el color de la selección de pestañas en lugar del color azul:

  1. Seleccione el TabItem.
  2. Desde "Mostrar el inspector de identidad" en el menú del lado derecho.
  3. Establece el atributo "tintColor" con el color que prefieras.

introduzca la descripción de la imagen aquí

 7
Author: Ahmed Lotfy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-11 14:47:16

La nueva respuesta para hacer esto programáticamente a partir de iOS 10 + con Swift 3 es usar el unselectedItemTintColor API. Por ejemplo, si ha inicializado su controlador de barra de pestañas dentro de su AppDelegate, tendría el siguiente aspecto:

 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

        ...
    }

Y para establecer los colores de texto seleccionados y no seleccionados:

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

self.tabBarItem.setTitleTextAttributes(unselectedItem, for: .normal)
self.tabBarItem.setTitleTextAttributes(selectedItem, for: .selected)
 4
Author: Anchor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-29 05:25:05

En Swift 3.0 puede escribirlo de la siguiente manera

Para la imagen de la barra de pestañas no seleccionada

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

Para la imagen seleccionada de la barra de pestañas

viewController.tabBarItem.selectedImage = UIImage(named: "image")?.withRenderingMode(.alwaysOriginal)
 3
Author: kbokdia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-12 14:45:25

Creo que la respuesta de @anka es bastante buena, y también agregué el siguiente código para habilitar el color de tinte para los elementos resaltados:

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

O en una línea:

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

Así que parece:

 2
Author: superarts.org,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-03 01:38:01

Solo necesita poner este código en su primer ViewController llamado para 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];
    }
 2
Author: Jose Pose S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-27 12:06:46

En lugar de agregar código de imagen de renderizado en cada ViewController para tabBarItem, use la extensión

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)
            }
        }
    }
}

Luego llame a esto en su clase UITabBarController como

class CustomTabBarViewController: UITabBarController {

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

Obtendrá una salida como : introduzca la descripción de la imagen aquí NOTA: No olvide asignar la clase CustomTabBarViewController a su TabBarController en storyboard.

 2
Author: Preeti Rani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-10 18:27:29

Solo necesitas poner este código en tu AppDelegate.m llamado (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]]; 
 1
Author: Amit Garg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-21 11:00:42

Si está buscando una solución iOS 11 swift 4, haga algo como esto en AppDelegate. Esto está cambiando todos los no seleccionados a negro.

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
}
 1
Author: thalacker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-15 18:19:18

La mejor manera de cambiar el color del elemento de la barra de pestañas seleccionado es agregar un solo código en appdelegate didFinishLaunchingWithOptions método

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

Cambiará el color del texto del elemento seleccionado

 0
Author: Sandu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-22 09:13:11

Puede hacerlo todo a través del creador de interfaces, verifique esta respuesta, muestra cómo hacer tanto activo como inactivo, "Cambiar el color seleccionado del elemento de la barra de pestañas en un guion gráfico"

 0
Author: Maria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:27

Para swift 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)
 0
Author: Mr. Tann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-07 08:09:16

Esto funcionó para mí SWIFT 3

viewConroller.tabBarItem = UITabBarItem(title: "", image: UIImage(named: "image")?.withRenderingMode(.alwaysOriginal),
                                selectedImage:  UIImage(named: "image"))
 -1
Author: zaido,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-08 07:23:16

Solución Swift : para el elemento NO SELECCIONADO : en cada ViewController - > viewDidLoad()

self.tabBarItem = UITabBarItem(title: nil, image: UIImage(named: "PHOTO_NAME")?.imageWithRenderingMode(.AlwaysOriginal), selectedImage: UIImage(named: "NAME"))
 -3
Author: Ben Siso,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-12 22:27:44