Barra de navegación del iPhone Color del texto del título

votos
272

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

Soy consciente del navigationItem.titleViewenfoque usando una imagen. Como 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.

Publicado el 01/03/2009 a las 07:51
fuente por usuario
En otros idiomas...                            


32 respuestas

votos
410

Enfoque moderno

La forma moderna, para todo el controlador de navegación ... hazlo una vez, cuando se cargue la vista raíz de tu controlador de navegación.

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

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

Enfoque clásico

La vieja forma, controlador de vista (estas constantes son para iOS 6, pero si quieres hacerlo por controlador de vista en iOS 7, querrás el mismo enfoque pero con constantes diferentes):

Necesitas usar a UILabelcomo the titleViewof the navigationItem.

La etiqueta debe:

  • Tener un color de fondo claro ( label.backgroundColor = [UIColor clearColor]).
  • Use la fuente del sistema en negrita de 20 pt ( label.font = [UIFont boldSystemFontOfSize: 20.0f]).
  • Tiene 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 de texto centrada ( label.textAlignment = NSTextAlignmentCenter( UITextAlignmentCenterpara SDK anteriores).

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

Lo resolví mediante prueba y error, pero los valores que obtuve son en última instancia demasiado simples para que no sean lo que Apple escogió. :)

Si desea verificar esto, la caída de este código en initWithNibName:bundle:en PageThreeViewController.mde muestra de barra de navegación de Apple . Esto reemplazará el texto con una etiqueta amarilla. Esto debería ser indistinguible del original producido por el código de Apple, a excepción del 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;
}

Editar: 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.

Respondida el 07/03/2009 a las 03:30
fuente por usuario

votos
226

Sé que esto es un hilo bastante viejo, pero yo creo que sería útil conocer a los nuevos usuarios que iOS 5 trae una nueva propiedad para establecer propiedades del título.

Puede utilizar UINavigationBar de setTitleTextAttributespara establecer el tipo de letra, color, offset, y la sombra de color.

Además se puede establecer el mismo defecto Título Texto de UINavigationBar Atributos para todo el UINavigationBarslargo de su aplicación.

Por ejemplo, así:

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

[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
Respondida el 26/10/2011 a las 23:16
fuente por usuario

votos
180

En iOS 5 se puede cambiar el color del título navigationbar de esta manera:

navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};
Respondida el 26/02/2012 a las 17:31
fuente por usuario

votos
127

Sobre la base de la respuesta de Steven Fisher escribí esta pieza 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 adecuadamente con el marco, es que si cambia el título de su controlador de la vista título personalizado también se actualizará. No hay necesidad de actualizar manualmente.

Otra gran ventaja es que hace que sea muy simple para permitir el color título personalizado. Todo lo que necesita hacer es añadir este método para el controlador.

Respondida el 05/05/2011 a las 14:52
fuente por usuario

votos
40

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

NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys: 
                               [UIColor whiteColor],NSForegroundColorAttributeName, 
                               [UIColor whiteColor],NSBackgroundColorAttributeName,nil];

self.navigationController.navigationBar.titleTextAttributes = textAttributes;
self.title = @"Title of the Page";

Además, el pago y envío NSAttributedString.h para determinar diversas propiedades de texto que se podrían establecer.

Respondida el 03/10/2013 a las 13:01
fuente por usuario

votos
38

En iOS 7 y 8, se puede cambiar el color del título a digamos verde

self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor greenColor] forKey:NSForegroundColorAttributeName];
Respondida el 19/12/2013 a las 17:14
fuente por usuario

votos
20

Para mantener la cuestión de hasta al día, voy a añadir Alex RR solución, pero en Swift :

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

Lo que se traduce a:

introducir descripción de la imagen aquí

Respondida el 14/08/2015 a las 13:48
fuente por usuario

votos
13

Método 1 , puso en IB:

introducir descripción de la imagen aquí

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

navigationController?.navigationBar.barTintColor = UIColor.blackColor()
Respondida el 08/04/2016 a las 10:45
fuente por usuario

votos
13

A partir de iOS 5 en adelante tenemos que establecer título color del texto y la fuente de la barra de navegación utilizando titleTextAttribute Dictionary (Diccionario predefinido en UInavigation referencia de clase controlador).

 [[UINavigationBar appearance] setTitleTextAttributes:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [UIColor blackColor],UITextAttributeTextColor, 
[UIFont fontWithName:@"ArialMT" size:16.0], UITextAttributeFont,nil]];
Respondida el 11/09/2012 a las 08:21
fuente por usuario

votos
13

La solución por tewha funciona bien si usted está tratando de cambiar el color de una página, pero yo quiero ser capaz de cambiar el color en todas las páginas. Hice algunas pequeñas modificaciones para que funcionaría para todos páginas en unaUINavigationController

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
Respondida el 24/09/2010 a las 03:56
fuente por usuario

votos
10

Swift Versión

Me pareció que la mayoría de ustedes presentó las respuestas de la versión Objective_C

Me gustaría implementar esta función mediante el uso de Swift para cualquiera que lo necesite.

en viewDidLoad

1.To hacer navigationbar fondo se convierte en color (por ejemplo: AZUL)

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

2.To hacer navigationbar fondo se convierte en imagen (por ejemplo: ABC.png)

let barMetrix = UIBarMetrics(rawValue: 0)!

self.navigationController?.navigationBar
      .setBackgroundImage(UIImage(named: "ABC"), forBarMetrics: barMetrix)

cambio 3.To título navigationbar (por ejemplo: [Fuente: Futura, 10] [Color: rojo])

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

(Hint1: "!" No se olvide de la marca después de la UIFont)

(Hint2: hay un montón de atributos del texto del título, comando haga clic en el "NSFontAttributeName" puede introducir los nombres clave de clase y ver y los tipos de objetos que se requiere)

Espero que pueda ayudar!: D

Respondida el 09/10/2015 a las 07:05
fuente por usuario

votos
10

Utilice el código a continuación en cualquier viewDidLoad controlador de vista o método viewWillAppear.

- (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.
}
Respondida el 19/05/2014 a las 07:43
fuente por usuario

votos
9

Corto y dulce.

[[[self navigationController] navigationBar] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];
Respondida el 08/12/2013 a las 03:50
fuente por usuario

votos
8

Esto se basa en mi solución Stevens

La única diferencia real es que poner un poco de manipulación en para ajustar la posición si dependiendo de la longitud del texto, parece ser similar a la forma de la manzana hacerlo

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 para ajustar el valor 10 dependiendo de su tamaño de la fuente

Respondida el 22/10/2010 a las 15:28
fuente por usuario

votos
6

Es un tema bastante viejo, pero creo que de proporcionar respuesta para ajuste de color, tamaño y la posición vertical de la barra de navegación del título para iOS 7 y por encima

Para Color y Tamaño

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

Por Posición 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;
Respondida el 04/06/2015 a las 15:05
fuente por usuario

votos
6

Se recomienda ajustar self.title ya que se utiliza mientras se empuja navbars niño o mostrar título en tabbars.

- (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];
    }
}
Respondida el 24/05/2012 a las 19:50
fuente por usuario

votos
6

He personalizado imagen de fondo de la navigationbar y dejó elemento botón, y el título gris no encaja en el fondo. Luego uso:

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

para cambiar el color de la tinta a gris. Y el título es blanco ahora! Eso es lo que quiero.

Esperanza para ayudar también :)

Respondida el 27/05/2011 a las 06:37
fuente por usuario

votos
6

Me encontré con el problema con mis botones de navegación lanzando el texto fuera del centro (cuando sólo tiene un botón). Para corregir esto acabo de cambiar mi tamaño de la trama de esta manera:

CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
Respondida el 21/01/2011 a las 17:07
fuente por usuario

votos
4

Esto funciona para mí en Swift:

navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
Respondida el 12/04/2017 a las 23:44
fuente por usuario

votos
4

Utilizar así por el apoyo 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];
Respondida el 17/01/2011 a las 06:28
fuente por usuario

votos
3

Una actualización para el post de Alex RR utilizando el nuevo iOS 7 atributos de texto y c objetivo moderna 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];
Respondida el 29/11/2013 a las 23:35
fuente por usuario

votos
3

para ajustar el tamaño de fuente del título que he utilizado las siguientes condiciones .. tal vez atento a cualquiera

if ([currentTitle length]>24) msize = 10.0f;
    else if ([currentTitle length]>16) msize = 14.0f;
    else if ([currentTitle length]>12) msize = 18.0f;
Respondida el 15/09/2011 a las 12:18
fuente por usuario

votos
2

Creo forma correcta de establecer el color de UINavigationBar es:

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

El código de seguridad que está escrito es subclase de UINavigationBar, obviamente, funciona sin la subclasificación también.

Respondida el 09/07/2012 a las 23:04
fuente por usuario

votos
2

Después de encontrarse con 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 ruleta que puedo reemplazar con un botón cuando se carga la fecha), las soluciones anteriores no funcionaron para mí, así que aquí es lo que funcionó y se mantiene 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;
Respondida el 14/04/2011 a las 22:23
fuente por usuario

votos
2

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

Respondida el 01/03/2009 a las 08:11
fuente por usuario

votos
1
 self.navigationItem.title=@"Extras";
    [self.navigationController.navigationBar setTitleTextAttributes:
     [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaNeue" size:21],
      NSFontAttributeName,[UIColor whiteColor],UITextAttributeTextColor,nil]];
Respondida el 30/10/2014 a las 05:39
fuente por usuario

votos
1

titleTextAttributes mostrar los atributos de texto del título de la barra.

@property (no atómica, copiar) NSDictionary * titleTextAttributes Discusión Se puede especificar el tipo de letra, color de texto, color de texto de la sombra, y la sombra de texto compensado por el título en los atributos de texto de diccionario, utilizando las teclas de atributos de texto que se describen en NSString UIKit Adiciones de referencia.

Disponibilidad Disponible en iOS 5.0 y posterior. Declarado En UINavigationBar.h

Respondida el 07/10/2012 a las 06:51
fuente por usuario

votos
1

Se puede utilizar este método en el archivo de AppDelegate y se puede utilizar en todas las vistas

+(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;
}
Respondida el 20/08/2012 a las 11:47
fuente por usuario

votos
1

Debe llamar [etiqueta sizeToFit]; después de ajustar el texto para evitar desplazamientos extraños cuando la etiqueta se vuelve a colocar automáticamente en el título de la vista cuando otros botones ocupan la barra de navegación.

Respondida el 16/03/2011 a las 06:11
fuente por usuario

votos
0

Swift versión 4:

self.navigationController.navigationBar.titleTextAttributes = [
        NSAttributedStringKey.foregroundColor: UIColor.green]
Respondida el 23/06/2018 a las 08:41
fuente por usuario

votos
0

Estoy utilizando a continuación el código para iOS 9 y su funcionamiento muy bien para mí. También he utilizar color de la sombra por el título.

self.navigationItem.title = @"MY NAV TITLE";
self.navigationController.navigationBar.barTintColor = [UIColor redColor];
self.navigationController.navigationBar.translucent = NO;
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
shadow.shadowOffset = CGSizeMake(0, 1);
[self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                       [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], NSForegroundColorAttributeName,
                                                       shadow, NSShadowAttributeName,
                                                       [UIFont fontWithName:@"HelveticaNeue-Light" size:21.0], NSFontAttributeName, nil]];

Puede que esto le ayudará.

Gracias

Respondida el 12/07/2016 a las 03:40
fuente por usuario

votos
0

Con el fin de hacer gran solución de Erik B más utilizable a través de las diferentes UIViewControllers de su aplicación Recomiendo añadir una categoría para UIViewController y declarar su setTitle: Método del título en el interior. Como no obtendrá el cambio de color del título en todos los controladores de vista sin la necesidad de la duplicación.

Una cosa a destacar es que aunque no es necesario [súper setTitle: Tilte]; en el código de Erik y que tendrá que llamar explícitamente self.title = @ "mi nuevo título" en sus controladores de vista de este método a ser llamado

@implementation UIViewController (CustomeTitleColor)

- (void)setTitle:(NSString *)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 blueColor]; // Change to desired color

        self.navigationItem.titleView = titleView;
        [titleView release];
    }
    titleView.text = title;
    [titleView sizeToFit];
}

@fin

Respondida el 31/12/2012 a las 11:48
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more