color bar ios iphone uinavigationbar

ios - Color de texto del título de la barra de navegación del iPhone



navigation bar swift 4 (30)

Parece que el color del título de la barra de navegación de iOS es blanco por defecto. ¿Hay una manera de cambiarlo a un color diferente?

Soy consciente de que el enfoque de navigationItem.titleView utiliza una imagen. Ya que mis habilidades de diseño son limitadas y no pude obtener el brillo estándar, prefiero cambiar el color del texto.

Cualquier idea sería muy apreciada.


Enfoque moderno

La forma moderna, para todo el controlador de navegación ... haga esto una vez, cuando se carga la vista raíz de su controlador de navegación.

[self.navigationController.navigationBar setTitleTextAttributes: @{NSForegroundColorAttributeName:[UIColor yellowColor]}];

Sin embargo, esto no parece tener efecto en vistas posteriores.

Enfoque clásico

De la forma anterior, el controlador por vista (estas constantes son para iOS 6, pero si quiere hacerlo por vista en el aspecto de iOS 7, querrá el mismo enfoque pero con diferentes constantes):

UILabel usar una UILabel como el titleView del titleView de navigationItem .

La etiqueta debe:

  • Tenga un color de fondo claro ( label.backgroundColor = [UIColor clearColor] ).
  • Use la fuente del sistema bold 20pt ( label.font = [UIFont boldSystemFontOfSize: 20.0f] ).
  • Tenga una sombra de negro con un 50% de alfa ( label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5] ).
  • También querrá establecer la alineación del texto en centrado ( label.textAlignment = NSTextAlignmentCenter ( UITextAlignmentCenter para SDK más antiguos).

Establezca el color del texto de la etiqueta para que sea el color personalizado que desee. Desea un color que no haga que el texto se mezcle con la sombra, lo que sería difícil de leer.

Resolví esto a través de prueba y error, pero los valores que obtuve son, en última instancia, demasiado simples para que no sean lo que Apple eligió. :)

Si desea verificar esto, coloque este código en initWithNibName:bundle: en PageThreeViewController.m de la muestra PageThreeViewController.m de Apple . Esto reemplazará el texto con una etiqueta amarilla. Esto debería ser indistinguible del original producido por el código de Apple, excepto el color.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // this will appear as the title in the navigation bar UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease]; label.backgroundColor = [UIColor clearColor]; label.font = [UIFont boldSystemFontOfSize:20.0]; label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]; label.textAlignment = NSTextAlignmentCenter; // ^-Use UITextAlignmentCenter for older SDKs. label.textColor = [UIColor yellowColor]; // change this color self.navigationItem.titleView = label; label.text = NSLocalizedString(@"PageThreeTitle", @""); [label sizeToFit]; } return self; }

Edición: También, lea la respuesta de Erik B a continuación. Mi código muestra el efecto, pero su código ofrece una forma más sencilla de colocar esto en su lugar en un controlador de vista existente.


A partir de iOS 5, debemos configurar el color del texto del título y la fuente de la barra de navegación utilizando el diccionario de atributos de título de texto (diccionario predefinido en la referencia de clase del controlador UInavigation).

[[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [UIColor blackColor],UITextAttributeTextColor, [UIFont fontWithName:@"ArialMT" size:16.0], UITextAttributeFont,nil]];


Basándome en la respuesta de Steven Fisher, escribí este fragmento de código:

- (void)setTitle:(NSString *)title { [super setTitle:title]; UILabel *titleView = (UILabel *)self.navigationItem.titleView; if (!titleView) { titleView = [[UILabel alloc] initWithFrame:CGRectZero]; titleView.backgroundColor = [UIColor clearColor]; titleView.font = [UIFont boldSystemFontOfSize:20.0]; titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]; titleView.textColor = [UIColor yellowColor]; // Change to desired color self.navigationItem.titleView = titleView; [titleView release]; } titleView.text = title; [titleView sizeToFit]; }

La ventaja de este código, además de tratar con el marco correctamente, es que si cambia el título de su controlador, la vista del título personalizado también se actualizará. No es necesario actualizarlo manualmente.

Otra gran ventaja es que hace que sea realmente sencillo habilitar el color del título personalizado. Todo lo que necesita hacer es agregar este método al controlador.


Corto y dulce.

[[[self navigationController] navigationBar] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];


Creo que la forma correcta de establecer el color de UINavigationBar es:

NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],UITextAttributeTextColor, nil]; self.titleTextAttributes = attributes;

El código anterior está escrito es subclase en UINavigationBar , obviamente también funciona sin subclases.


Debe llamar [label sizeToFit]; después de configurar el texto para evitar compensaciones extrañas cuando la etiqueta se reposiciona automáticamente en la vista de título cuando otros botones ocupan la barra de navegación.


Después de encontrar el mismo problema (como otros) de la etiqueta que se mueve cuando insertamos un botón en la barra de navegación (en mi caso, tengo una rueda giratoria que reemplazo con un botón cuando se carga la fecha), las soluciones anteriores no funcionaron para mí, aquí está lo que funcionó y mantuvo la etiqueta en el mismo lugar todo el tiempo:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // this will appear as the title in the navigation bar //CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44); CGRect frame = CGRectMake(0, 0, 180, 44); UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease]; label.backgroundColor = [UIColor clearColor]; label.font = [UIFont boldSystemFontOfSize:20.0]; label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]; label.textAlignment = UITextAlignmentCenter; label.textColor = [UIColor yellowColor]; self.navigationItem.titleView = label; label.text = NSLocalizedString(@"Latest Questions", @""); [label sizeToFit]; } return self;


En IOS 7 y 8, puedes cambiar el color del título para decir verde

self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor greenColor] forKey:NSForegroundColorAttributeName];


En iOS 5 puedes cambiar el color del título de la barra de navegación de esta manera:

navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};


Esta es mi solución basada en Stevens.

La única diferencia real es que pongo algo de manejo para ajustar la posición si, dependiendo de la longitud del texto, parece ser similar a cómo lo hace Apple.

UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft), 0, 480,44)]; titleLabel.backgroundColor = [UIColor clearColor]; titleLabel.font = [UIFont boldSystemFontOfSize: 20.0f]; titleLabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]; titleLabel.textAlignment = ([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft); titleLabel.textColor = [UIColor redColor]; titleLabel.text = self.title; self.navigationItem.titleView = titleLabel; [titleLabel release];

Es posible que desee ajustar el valor de 10 en función de su tamaño de fuente


Esta es una de esas cosas que faltan. Lo mejor que puedes hacer es crear tu propia barra de navegación personalizada, agregar un cuadro de texto y manipular el color de esa manera.


Este es un hilo bastante antiguo, pero creo que es una respuesta para la configuración del color, el tamaño y la posición vertical del título de la barra de navegación para iOS 7 y superior

Para Color y Tamaño

NSDictionary *titleAttributes =@{ NSFontAttributeName :[UIFont fontWithName:@"Helvetica-Bold" size:14.0], NSForegroundColorAttributeName : [UIColor whiteColor] };

Para posicion vertical

[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:-10.0 forBarMetrics:UIBarMetricsDefault];

Establecer título y asignar el diccionario de atributos.

[[self navigationItem] setTitle:@"CLUBHOUSE"]; self.navigationController.navigationBar.titleTextAttributes = titleAttributes;


Esto funciona para mí en Swift:

navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]


He personalizado la imagen de fondo de la barra de navegación y el elemento del botón izquierdo, y el título gris no se ajusta al fondo. Luego uso:

[self.navigationBar setTintColor:[UIColor darkGrayColor]];

Para cambiar el color del tinte a gris. ¡Y el título es blanco ahora! Eso es lo que quiero.

Espero poder ayudar también :)


La mayoría de las sugerencias anteriores están en desuso ahora, para uso de iOS 7 -

NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor],NSForegroundColorAttributeName, [UIColor whiteColor],NSBackgroundColorAttributeName,nil]; self.navigationController.navigationBar.titleTextAttributes = textAttributes; self.title = @"Title of the Page";

Además, revise el NSAttributedString.h para varias propiedades de texto que se podrían establecer.


La solución de tewha funciona bien si intenta cambiar el color en una página, pero quiero poder cambiar el color en cada página. Hice algunas pequeñas modificaciones para que funcionara en todas las páginas de un UINavigationController

NavigationDelegate.h

//This will change the color of the navigation bar #import <Foundation/Foundation.h> @interface NavigationDelegate : NSObject<UINavigationControllerDelegate> { } @end

NavigationDelegate.m

#import "NavigationDelegate.h" @implementation NavigationDelegate - (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{ CGRect frame = CGRectMake(0, 0, 200, 44);//TODO: Can we get the size of the text? UILabel* label = [[[UILabel alloc] initWithFrame:frame] autorelease]; label.backgroundColor = [UIColor clearColor]; label.font = [UIFont boldSystemFontOfSize:20.0]; label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]; label.textAlignment = UITextAlignmentCenter; label.textColor = [UIColor yellowColor]; //The two lines below are the only ones that have changed label.text=viewController.title; viewController.navigationItem.titleView = label; } @end


Me encontré con el problema con mis botones de navegación lanzando el texto fuera del centro (cuando solo tienes un botón). Para arreglar eso, acabo de cambiar mi tamaño de marco así:

CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);


Para establecer el tamaño de fuente del título, he usado las siguientes condiciones. Tal vez sea útil para cualquiera.

if ([currentTitle length]>24) msize = 10.0f; else if ([currentTitle length]>16) msize = 14.0f; else if ([currentTitle length]>12) msize = 18.0f;


Para mantener la pregunta actualizada, agregaré la solución Alex RR , pero en Swift :

self.navigationController.navigationBar.barTintColor = .blueColor() self.navigationController.navigationBar.tintColor = .whiteColor() self.navigationController.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName : UIColor.whiteColor() ]

Que resulta para:


Puede usar este método en el archivo appdelegate y puede usar en cada vista

+(UILabel *) navigationTitleLable:(NSString *)title { CGRect frame = CGRectMake(0, 0, 165, 44); UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease]; label.backgroundColor = [UIColor clearColor]; label.font = NAVIGATION_TITLE_LABLE_SIZE; label.shadowColor = [UIColor whiteColor]; label.numberOfLines = 2; label.lineBreakMode = UILineBreakModeTailTruncation; label.textAlignment = UITextAlignmentCenter; [label setShadowOffset:CGSizeMake(0,1)]; label.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0]; //label.text = NSLocalizedString(title, @""); return label; }


Sé que este es un hilo bastante antiguo, pero creo que sería útil saber para los nuevos usuarios que iOS 5 trae una nueva propiedad para establecer las propiedades del título.

Puede usar setTitleTextAttributes de setTitleTextAttributes para configurar la fuente, el color, el desplazamiento y el color de la sombra.

Además, puede configurar los mismos Atributos de Texto de Título de UINavigationBar para todos los UINavigationBars toda su aplicación.

Por ejemplo como asi:

NSDictionary *navbarTitleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor],UITextAttributeTextColor, [UIColor blackColor], UITextAttributeTextShadowColor, [NSValue valueWithUIOffset:UIOffsetMake(-1, 0)], UITextAttributeTextShadowOffset, nil]; [[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];


Se recomienda establecer self.title ya que se usa al presionar barras de navegación secundarias o mostrar el título en las barras de tabulación.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // create and customize title view self.title = NSLocalizedString(@"My Custom Title", @""); UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero]; titleLabel.text = self.title; titleLabel.font = [UIFont boldSystemFontOfSize:16]; titleLabel.backgroundColor = [UIColor clearColor]; titleLabel.textColor = [UIColor whiteColor]; [titleLabel sizeToFit]; self.navigationItem.titleView = titleLabel; [titleLabel release]; } }


Una actualización de la publicación de Alex RR con los nuevos atributos de texto de iOS 7 y el moderno objetivo c para reducir el ruido:

NSShadow *titleShadow = [[NSShadow alloc] init]; titleShadow.shadowColor = [UIColor blackColor]; titleShadow.shadowOffset = CGSizeMake(-1, 0); NSDictionary *navbarTitleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor], NSShadowAttributeName:titleShadow}; [[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];


Use el código a continuación en cualquier controlador viewDidLoad o viewWillAppear del controlador.

- (void)viewDidLoad { [super viewDidLoad]; //I am using UIColor yellowColor for an example but you can use whatever color you like self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]}; //change the title here to whatever you like self.title = @"Home"; // Do any additional setup after loading the view. }


Utilice así para soporte de orientación

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,40)]; [view setBackgroundColor:[UIColor clearColor]]; [view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ]; UILabel *nameLabel = [[UILabel alloc] init]; [nameLabel setFrame:CGRectMake(0, 0, 320, 40)]; [nameLabel setBackgroundColor:[UIColor clearColor]]; [nameLabel setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin |UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin]; [nameLabel setTextColor:[UIColor whiteColor]]; [nameLabel setFont:[UIFont boldSystemFontOfSize:17]]; [nameLabel setText:titleString]; [nameLabel setTextAlignment:UITextAlignmentCenter]; [view addSubview:nameLabel]; [nameLabel release]; self.navigationItem.titleView = view; [view release];


Versión rápida

Encontré que la mayoría de ustedes presentaron las respuestas de la versión Objective_C

Me gustaría implementar esta función utilizando Swift para cualquier persona que la necesite.

En ViewDidload

1.Para que el fondo de la barra de navegación se convierta en color (por ejemplo: AZUL)

self.navigationController?.navigationBar.barTintColor = UIColor.blueColor()

2.Para que el fondo de la Barra de navegación se convierta en Imagen (por ejemplo: ABC.png)

let barMetrix = UIBarMetrics(rawValue: 0)! self.navigationController?.navigationBar .setBackgroundImage(UIImage(named: "ABC"), forBarMetrics: barMetrix)

3. Para cambiar el título de la barra de navegación (por ejemplo: [Fuente: Futura, 10] [Color: Rojo])

navigationController?.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName : UIColor.redColor(), NSFontAttributeName : UIFont(name: "Futura", size: 10)! ]

(pista 1: no olvide la marca "!" después de UIFont)

(hint2: hay muchos atributos del texto del título, haga clic en el comando "NSFontAttributeName" para ingresar la clase y ver los nombres clave y los tipos de objetos que requieren)

Espero poder ayudar!: D


Versión Swift 4:

self.navigationController.navigationBar.titleTextAttributes = [ NSAttributedStringKey.foregroundColor: UIColor.green]


titleTextAttributes Muestra atributos para el texto del título de la barra.

@property (nonatomic, copy) NSDictionary * titleTextAttributes Discusión Puede especificar la fuente, el color del texto, el color de la sombra del texto y el desplazamiento de la sombra del texto en el diccionario de atributos de texto, utilizando las claves de los atributos de texto que se describen en la Referencia de adiciones del NSItral UIKit.

Disponibilidad disponible en iOS 5.0 y versiones posteriores. Declarado en UINavigationBar.h


Método 1 , configurarlo en IB:

Método 2 , una línea de código:

navigationController?.navigationBar.barTintColor = UIColor.blackColor()


self.navigationItem.title=@"Extras"; [self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaNeue" size:21], NSFontAttributeName,[UIColor whiteColor],UITextAttributeTextColor,nil]];