¿Color UITabBar no seleccionado?


Tengo un UITabBar con 5 elementos. Quiero cambiar el color no seleccionado de todos los elementos. Los elementos no se declaran en las clases UIViewController (los construí y vinculé las vistas en el Storyboard).

Hay un código como este : [[UITabBar appearance] set***UN***SelectedImageTintColor:[UIColor whiteColor]]; ?

Author: the Tin Man, 2012-07-17

11 answers

ASÍ que dice que no puedo eliminar la respuesta aceptada (lo intenté), pero obviamente, hay muchos votos positivos para los comentarios que esto no funciona para iOS 7.

Vea la otra respuesta a continuación con muchos más votos positivos, o el enlace en el comentario de @Liam a esta respuesta.


solo para iOS 6

Debería ser tan simple como esto:

[[UITabBar appearance] setTintColor:[UIColor grayColor]]; // for unselected items that are gray
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]]; // for selected items that are green
 16
Author: john.k.doe,
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-05-21 20:14:59

Esto no funcionará en iOS 7 por lo que puedo decir. En particular, tintColor de la barra de pestañas definirá el color de la pestaña seleccionada, no de las no seleccionadas. Si desea cambiar el valor predeterminado en iOS 7, parece que en realidad tiene que usar diferentes iconos (en el color que desea tener para las pestañas no seleccionadas) y establecer el color del texto.

Este ejemplo debe teñir las pestañas seleccionadas de rojo y representar otras en verde. Ejecutar este código en su TabBarController:

// set color of selected icons and text to red
self.tabBar.tintColor = [UIColor redColor];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor redColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];


// set color of unselected text to green
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor greenColor], NSForegroundColorAttributeName, nil]
                                         forState:UIControlStateNormal];

// set selected and unselected icons
UITabBarItem *item0 = [self.tabBar.items objectAtIndex:0];

// this way, the icon gets rendered as it is (thus, it needs to be green in this example)
item0.image = [[UIImage imageNamed:@"unselected-icon.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

// this icon is used for selected tab and it will get tinted as defined in self.tabBar.tintColor
item0.selectedImage = [UIImage imageNamed:@"selected-icon.png"];

Si configura el icono solo en el story board, solo puede controlar el color de la pestaña seleccionada (tintColor). Todos los demás iconos y el texto correspondiente se dibujarán en gris.

Tal vez alguien sabe una manera más fácil de adoptar los colores bajo iOS 7?

 94
Author: Sven Tiffe,
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-04-08 04:18:20

Extendiendo la respuesta de @Sven Tiffe para iOS 7, puede obtener su código para teñir automáticamente las imágenes UITabBar no seleccionadas agregadas en el guion gráfico. El siguiente enfoque le ahorrará tener que crear dos conjuntos de imágenes de iconos (es decir, seleccionados vs no seleccionados)y tener que cargarlos programáticamente. Agregue el método category imageWithColor: (vea - Cómo puedo cambiar image tintColor en iOS y WatchKit ) a su proyecto luego coloque lo siguiente en su UITabBarController viewDidLoad personalizado método:

// set the selected colors
[self.tabBar setTintColor:[UIColor whiteColor]];
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName, nil] forState:UIControlStateSelected];


UIColor * unselectedColor = [UIColor colorWithRed:184/255.0f green:224/255.0f blue:242/255.0f alpha:1.0f];

// set color of unselected text
[[UITabBarItem appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:unselectedColor, NSForegroundColorAttributeName, nil]
                                         forState:UIControlStateNormal];

// generate a tinted unselected image based on image passed via the storyboard
for(UITabBarItem *item in self.tabBar.items) {
    // use the UIImage category code for the imageWithColor: method
    item.image = [[item.selectedImage imageWithColor:unselectedColor] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}

Cree una categoría llamada UIImage+Overlay y en UIImage+Overlay.m (extraído de esta respuesta ) :

@implementation UIImage(Overlay)

- (UIImage *)imageWithColor:(UIColor *)color1
{
        UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(context, 0, self.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextSetBlendMode(context, kCGBlendModeNormal);
        CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
        CGContextClipToMask(context, rect, self.CGImage);
        [color1 setFill];
        CGContextFillRect(context, rect);
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
}
@end
 68
Author: user3719695,
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:03:07

En iOS 10 y superior (!), hay 3 soluciones fáciles posibles:

  1. Instancia de código (swift):

    Auto.TabBar.unselectedItemTintColor = unselectedcolor

  2. Instancia de IB:

    Añadir una ruta de acceso de clave: unselectedItemTintColor

    De tipo: Color

  3. Apariencia global (swift):

    UITabBar.apariencia().unselectedItemTintColor = unselectedcolor

 55
Author: vtcajones,
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-12-07 10:41:15

Traduciendo la respuesta de user3719695 a Swift, que ahora usa extensiones:

UIImage + Superposición.swift

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, CGBlendMode.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
  }
}

CustomTabBar.swift

override func viewDidLoad() {
  super.viewDidLoad()
  for item in self.tabBar.items! {
    item.image = item.selectedImage?.imageWithColor(unselectedColor).imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
    //In case you wish to change the font color as well
    let attributes = [NSForegroundColorAttributeName: unselectedColor]
    item.setTitleTextAttributes(attributes, forState: UIControlState.Normal)
  }
}
 16
Author: JoeGalind,
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-10-17 00:50:12

Versión Swift en iOS 10 y superior -

UITabBar.appearance().tintColor = UIColor.gray
UITabBar.appearance().unselectedItemTintColor = UIColor.gray
 11
Author: Abhishek Jain,
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-07 10:29:03

Tuve que mover el código a viewWillAppear porque en viewDidLoad las imágenes aún no estaban configuradas.

Swift 4 Traducción

import Foundation
import UIKit

extension UIImage {
    func with(color: UIColor) -> UIImage {
        guard let cgImage = self.cgImage else {
            return self
        }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let context = UIGraphicsGetCurrentContext()!
        context.translateBy(x: 0, y: size.height)
        context.scaleBy(x: 1.0, y: -1.0)
        context.setBlendMode(.normal)
        let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        context.clip(to: imageRect, mask: cgImage)
        color.setFill()
        context.fill(imageRect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext();
        return newImage
    }
}

class MYTabBarController: UITabBarController {

    let unselectedColor = UIColor(red: 108/255.0, green: 110/255.0, blue: 114/255.0, alpha: 1.0)
    let selectedColor = UIColor.blue()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // Unselected state colors
        for item in self.tabBar.items! {
            item.image = item.selectedImage!.with(color: unselectedColor).withRenderingMode(.alwaysOriginal)
        }
        UITabBarItem.appearance().setTitleTextAttributes([.foregroundColor : unselectedColor], for: .normal)

        // Selected state colors
        tabBar.tintColor = selectedColor
        UITabBarItem.appearance().setTitleTextAttributes([.foregroundColor : selectedColor], for: .selected)
    }
}
 5
Author: kgaidis,
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-03-05 00:08:13

Refiriéndose a la respuesta de aquí: UITabBar tinte en iOS 7

Puede establecer el color de tinte para los botones de la barra de pestañas seleccionados y no seleccionados como este:

[[UIView appearanceWhenContainedIn:[UITabBar class], nil] setTintColor:[UIColor redColor]];
[[UITabBar appearance] setSelectedImageTintColor:[UIColor greenColor]];

La primera línea establece el color no seleccionado - rojo en este ejemplo - estableciendo el color Tint de UIView cuando está contenido en una barra de pestañas. Tenga en cuenta que esto solo establece el color de tinte de la imagen no seleccionada, no cambia el color del texto debajo de ella.

La segunda línea establece el tinte de imagen seleccionado de la barra de pestañas color a verde.

 1
Author: Benkax,
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:03:07

La nueva respuesta para hacer esto programáticamente a partir de iOS 10+ 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

        ...
    }
 1
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:11:27

Versión Swift 4 (Sin desenvolver implícitamente los Opcionales) :

UIImage + Superposición.swift

import UIKit

extension UIImage {
    func with(color: UIColor) -> UIImage? {
        guard let cgImage = self.cgImage else {
            return self
        }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        if let context = UIGraphicsGetCurrentContext() {
            context.translateBy(x: 0, y: size.height)
            context.scaleBy(x: 1.0, y: -1.0)
            context.setBlendMode(.normal)
            let imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            context.clip(to: imageRect, mask: cgImage)
            color.setFill()
            context.fill(imageRect)
            if let newImage = UIGraphicsGetImageFromCurrentImageContext() {
                UIGraphicsEndImageContext();
                return newImage
            }
        }
        return nil;
    }
}


CustomTabBarController.swift

class CustomTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 10.0, *) {
            self.tabBar.unselectedItemTintColor = UIColor.init(white: 1, alpha: 0.5)
        } else {
            // Fallback on earlier versions
            if let items = self.tabBar.items {
                let unselectedColor = UIColor.init(white: 1, alpha: 0.5)
                let selectedColor = UIColor.white
                // Unselected state colors
                for item in items {
                    if let selectedImage = item.selectedImage?.with(color: unselectedColor)?.withRenderingMode(.alwaysOriginal) {
                        item.image = selectedImage
                    }
                }
                UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : unselectedColor], for: .normal)

                // Selected state colors
                tabBar.tintColor = selectedColor
                UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : selectedColor], for: .selected)
            }
        }

        UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.font: UIFont(name: "overpass-light", size: 12)!, NSAttributedStringKey.foregroundColor: UIColor.white], for: UIControlState.normal)
    }
}
 1
Author: AhmedZah,
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-11-15 14:26:40

@JoeGalid imageWithColor: solución con Xamarin:

using CoreGraphics;
using UIKit;

namespace Example
{
    public static class UIImageExtensions
    {
        public static UIImage ImageWithColor(this UIImage image, UIColor color)
        {
            UIGraphics.BeginImageContextWithOptions(image.Size, false, image.CurrentScale);

            color.SetFill();

            var context = UIGraphics.GetCurrentContext();

            context.TranslateCTM(0, image.Size.Height);
            context.ScaleCTM(1.0f, -1.0f);
            context.SetBlendMode(CoreGraphics.CGBlendMode.Normal);

            var rect = new CGRect(0, 0, image.Size.Width, image.Size.Height);
            context.ClipToMask(rect, image.CGImage);
            context.FillRect(rect);

            var newImage = UIGraphics.GetImageFromCurrentImageContext() as UIImage;
            UIGraphics.EndImageContext();

            return newImage;
        }
    }
}

Luego utilícelo al configurar los elementos de la barra de pestañas:

var image = UIImage.FromBundle("name");
barItem.Image = image.ImageWithColor(UIColor.Gray).ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
barItem.SelectedImage = image.ImageWithColor(UIColor.Red).ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal)
 0
Author: JAM,
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-09-06 12:47:46