Cambio de tinte / Color de fondo de UITabBar


La UINavigationBar y la UISearchBar tienen una propiedad tintColor que le permite cambiar el color del tinte (sorprendente, lo sé) de ambos elementos. Quiero hacer lo mismo con UITabBar en mi aplicación, pero ahora he encontrado la forma de cambiarlo del color negro predeterminado. Alguna idea?

Author: pixel, 2009-02-20

18 answers

He podido hacer que funcione subclasificando un UITabBarController y usando clases privadas:

@interface UITabBarController (private)
- (UITabBar *)tabBar;
@end

@implementation CustomUITabBarController


- (void)viewDidLoad {
    [super viewDidLoad];

    CGRect frame = CGRectMake(0.0, 0.0, self.view.bounds.size.width, 48);
    UIView *v = [[UIView alloc] initWithFrame:frame];
    [v setBackgroundColor:kMainColor];
    [v setAlpha:0.5];
    [[self tabBar] addSubview:v];
    [v release];

}
@end
 48
Author: coneybeare,
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
2009-03-14 17:17:56

IOS 5 ha añadido algunos nuevos métodos de apariencia para personalizar el aspecto de la mayoría de los elementos de la interfaz de usuario.

Puede dirigirse a cada instancia de un UITabBar en su aplicación mediante el proxy de apariencia.

Para iOS 5 + 6:

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

Para iOS 7 y superiores, utilice lo siguiente:

[[UITabBar appearance] setBarTintColor:[UIColor redColor]];

El uso del proxy de apariencia cambiará cualquier instancia de barra de pestañas en toda la aplicación. Para una instancia específica, utilice una de las nuevas propiedades de esa clase:

UIColor *tintColor; // iOS 5+6
UIColor *barTintColor; // iOS 7+
UIColor *selectedImageTintColor;
UIImage *backgroundImage;
UIImage *selectionIndicatorImage;
 104
Author: imnk,
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-12-17 11:03:40

Tengo una adición a la respuesta final. Si bien el esquema esencial es correcto, el truco de usar un color parcialmente transparente se puede mejorar. Asumo que es sólo para dejar que el gradiente predeterminado para mostrar a través. Oh, también, la altura de la barra de pestañas es de 49 píxeles en lugar de 48, al menos en OS 3.

Por lo tanto, si tiene una imagen apropiada de 1 x 49 con un degradado, esta es la versión de viewDidLoad que debe usar:

- (void)viewDidLoad {

    [super viewDidLoad]; 

    CGRect frame = CGRectMake(0, 0, 480, 49);
    UIView *v = [[UIView alloc] initWithFrame:frame];
    UIImage *i = [UIImage imageNamed:@"GO-21-TabBarColorx49.png"];
    UIColor *c = [[UIColor alloc] initWithPatternImage:i];
    v.backgroundColor = c;
    [c release];
    [[self tabBar] addSubview:v];
    [v release];

}
 34
Author: pabugeater,
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-03-31 07:50:22

Cuando solo usas addSubview tus botones perderán clickability, así que en lugar de

[[self tabBar] addSubview:v];

Uso:

[[self tabBar] insertSubview:v atIndex:0];
 27
Author: Marcin Zbijowski,
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
2013-01-21 17:49:20

Lo siguiente es la solución perfecta para esto. Esto funciona bien conmigo para iOS5 y iOS4.

//---- For providing background image to tabbar
UITabBar *tabBar = [tabBarController tabBar]; 

if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) {
    // ios 5 code here
    [tabBar setBackgroundImage:[UIImage imageNamed:@"image.png"]];
} 
else {
    // ios 4 code here
    CGRect frame = CGRectMake(0, 0, 480, 49);
    UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
    UIImage *tabbag_image = [UIImage imageNamed:@"image.png"];
    UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
    tabbg_view.backgroundColor = tabbg_color;
    [tabBar insertSubview:tabbg_view atIndex:0];
}
 7
Author: Gaurav,
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
2012-03-15 17:57:47

En iOS 7:

[[UITabBar appearance] setBarTintColor:[UIColor colorWithRed:(38.0/255.0) green:(38.0/255.0) blue:(38.0/255.0) alpha:1.0]];

También recomiendo configurar primero en función de sus deseos visuales:

[[UITabBar appearance] setBarStyle:UIBarStyleBlack];

El estilo de barra pone un sutil separador entre el contenido de la vista y la barra de pestañas.

 7
Author: capikaw,
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-01-02 18:46:44

No hay una forma sencilla de hacer esto, básicamente necesitas subclase UITabBar e implementar dibujo personalizado para hacer lo que quieras. Es un poco de trabajo para el efecto, pero puede valer la pena. Recomiendo presentar un error con Apple para agregarlo a un futuro SDK de iPhone.

 6
Author: Louis Gerbarg,
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
2009-02-20 20:11:21

[[self tabBar] insertSubview:v atIndex:0]; funciona perfectamente para mí.

 5
Author: jimmy,
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
2011-08-04 19:15:52

Para mí es muy simple cambiar el color de la Tabbar como : -

[self.TabBarController.tabBar setTintColor:[UIColor colorWithRed:0.1294 green:0.5686 blue:0.8353 alpha:1.0]];


[self.TabBarController.tabBar setTintColor:[UIColor "YOUR COLOR"];

¡Prueba esto!!!

 5
Author: Muhammad Rizwan,
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
2013-03-01 09:34:44
 [[UITabBar appearance] setTintColor:[UIColor redColor]];
 [[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];
 3
Author: Hsm,
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-10-31 01:16:24

Solo para el color de fondo

Tabbarcontroller.tabBar.barTintColor=[UIColor redcolour];

O esto en App Delegate

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

Para cambiar el color de los iconos deseleccionados de tabbar

Para 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]];
 2
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:24:30

Hay algunas buenas ideas en las respuestas existentes, muchas funcionan de manera ligeramente diferente y lo que elijas también dependerá de los dispositivos a los que apuntes y el tipo de aspecto que quieras lograr. UITabBar es notoriamente poco intuitivo cuando se trata de personalizar su apariencia, pero aquí hay algunos trucos más que pueden ayudar:

1). Si está buscando deshacerse de la superposición brillante para un aspecto más plano, haga lo siguiente:

tabBar.backgroundColor = [UIColor darkGrayColor]; // this will be your background
[tabBar.subviews[0] removeFromSuperview]; // this gets rid of gloss

2). Para configurar imágenes personalizadas en los botones de la barra de pestañas, haga algo como:

for (UITabBarItem *item in tabBar.items){
    [item setFinishedSelectedImage:selected withFinishedUnselectedImage:unselected];
    [item setImageInsets:UIEdgeInsetsMake(6, 0, -6, 0)];
}

Donde selected y unselected son UIImage objetos de su elección. Si quieres que sea un color plano, la solución más simple que encontré es crear un UIView con el backgroundColor deseado y luego renderizarlo en un UIImage con la ayuda de QuartzCore. Utilizo el siguiente método en una categoría en UIView para obtener un UIImage con el contenido de la vista:

- (UIImage *)getImage {
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [[UIScreen mainScreen]scale]);
    [[self layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

3) Finalmente, es posible que desee personalizar el estilo de los títulos de los botones. Do:

for (UITabBarItem *item in tabBar.items){
    [item setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                [UIColor redColor], UITextAttributeTextColor,
                [UIColor whiteColor], UITextAttributeTextShadowColor,
                [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset,
                [UIFont boldSystemFontOfSize:18], UITextAttributeFont,
            nil] forState:UIControlStateNormal];
}

Esto te permite hacer algunos ajustes, pero todavía bastante limitados. En particular, no puede modificar libremente dónde se coloca el texto dentro del botón, y no puede tener diferentes colores para los botones seleccionados/no seleccionados. Si desea hacer un diseño de texto más específico, simplemente configure UITextAttributeTextColor para que sea claro y agregue su texto a las imágenes selected y unselected de la parte (2).

 1
Author: SaltyNuts,
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
2013-02-28 19:17:55
[v setBackgroundColor ColorwithRed: Green: Blue: ];
 1
Author: Salim,
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-16 12:13:32

Otra solución (que es un truco) es establecer el alfa en el TabBarController a 0.01 para que sea virtualmente invisible pero aún así se puede hacer clic. A continuación, establezca un control ImageView en la parte inferior de la punta de la ventana principal con su imagen de barra de pestañas personalizada debajo del controlador de pestañas alpha ed. A continuación, cambie las imágenes, cambie los colores o hightlight cuando el tabbarcontroller cambie de vista.

Sin embargo, se pierde el '...más ' y personalizar la funcionalidad.

 0
Author: user855723,
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
2011-08-03 11:09:13

Hola estoy usando iOS SDK 4 y pude resolver este problema con solo dos líneas de código y es así

tBar.backgroundColor = [UIColor clearColor];
tBar.backgroundImage = [UIImage imageNamed:@"your-png-image.png"];

Espero que esto ayude!

 0
Author: Jorge Vicente Mendoza,
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
2011-12-22 17:55:18
if ([tabBar respondsToSelector:@selector(setBackgroundImage:)]) {
    // ios 5 code here
    [tabBar setBackgroundImage:[UIImage imageNamed:@"image.png"]];
} 
else {
    // ios 4 code here
    CGRect frame = CGRectMake(0, 0, 480, 49);
    UIView *tabbg_view = [[UIView alloc] initWithFrame:frame];
    UIImage *tabbag_image = [UIImage imageNamed:@"image.png"];
    UIColor *tabbg_color = [[UIColor alloc] initWithPatternImage:tabbag_image];
    tabbg_view.backgroundColor = tabbg_color;
    [tabBar insertSubview:tabbg_view atIndex:0];
}
 0
Author: user1049755,
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
2013-05-07 16:30:02

Swift 3.0 respuesta: (de Vaibhav Gaikwad)

Para cambiar el color de los iconos de deseleccionar de la tabbar:

if #available(iOS 10.0, *) {
        UITabBar.appearance().unselectedItemTintColor = UIColor.white
    } else {
        // Fallback on earlier versions
        for item in self.tabBar.items! {
            item.image = item.image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        }
}

Solo para cambiar el color del texto:

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

UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red, for: .selected)
 0
Author: odemolliens,
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-14 15:17:43

Swift 3 usando la apariencia de su AppDelegate haga lo siguiente:

UITabBar.appearance().barTintColor = your_color

 0
Author: Bobj-C,
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-04 18:49:26