2012-01-08 32 views
41

Tengo un UINavigationBar agregado a mi vista UIViewController. Quiero cambiar las propiedades de las fuentes. Tenga en cuenta que quiero cambiar un UINavigationBar no controlador. En mi aplicación donde uso UINavigationController utilizo self.navigationItem.titleView = label; para mostrar la etiqueta personalizada.¿Cambiar las propiedades de la fuente UINavigationBar?

¿Cómo puedo lograr tener un título personalizado en mi UINavigationBar?

P.S Lo utilizo para establecer el texto del título self.navBar.topItem.title = @"Information"; de mi UINavigationBar.

Respuesta

86

A partir de iOS 5, debemos establecer el color del texto del título y la fuente de la barra de navegación mediante el uso de titleTextAttribute Dictionary (diccionario predefinido en la referencia de clase del controlador de UInavigation).

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

El tutorial de abajo es el mejor tutorial para la personalización de la barra de UiElements como UInavigation, UIsegmented control, UITabBar. Esto puede ser útil para usted

http://www.raywenderlich.com/4344/user-interface-customization-in-ios-5

+2

@rolandjitsu, solo tiene que usar NSFontAttributeName en lugar de UITextAttributeFont. – CedricSoubrie

+1

@CedricSoubrie ~ sí, eso es cierto, solo quería informar al autor sobre eso para que podamos tener una respuesta actualizada :) – Roland

+3

Y UITextAttributeTextColor debe reemplazarse con NSForegroundColorAttributeName – bobmoff

21

(Esto no es posible con la nueva API de aspecto de iOS 5.0).

Editar:

iOS> = 5.0:

establecer el texto Título atributos para el navigationbar:

// Customize the title text for *all* UINavigationBars 
NSDictionary *settings = @{ 
    UITextAttributeFont     : [UIFont fontWithName:@"YOURFONTNAME" size:20.0], 
    UITextAttributeTextColor   : [UIColor whiteColor], 
    UITextAttributeTextShadowColor  : [UIColor clearColor], 
    UITextAttributeTextShadowOffset  : [NSValue valueWithUIOffset:UIOffsetZero]}; 

[[UINavigationBar appearance] setTitleTextAttributes:settings]; 

iOS 5.0 <

UINavigationItem no tiene una propiedad llamada etiqueta o algo así, solo un titleView. Sólo es capaz de establecer la fuente mediante el establecimiento de una etiqueta personalizada ya que este título de la vista podría utilizar el siguiente código: (como se sugiere here)

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)]; 
label.font = [UIFont fontWithName:@"YOURFONTNAME" size:20.0]; 
label.shadowColor = [UIColor clearColor]; 
label.textColor =[UIColor whiteColor]; 
label.text = self.title; 
self.navigationItem.titleView = label;  
[label release]; 
+0

De hecho, gracias por el comentario. No pude encontrarlo en ese momento. – Tieme

+0

MUCHAS GRACIAS :) – Abo3atef

7

sólo hay que poner esto en su aplicación del delegado

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 

De Ray Wenderlich:

http://www.raywenderlich.com/4344/user-interface-customization-in-ios-5

[[UINavigationBar appearance] setTitleTextAttributes: 
[NSDictionary dictionaryWithObjectsAndKeys: 
[UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0], 
UITextAttributeTextColor, 
[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8], 
UITextAttributeTextShadowColor, 
[NSValue valueWithUIOffset:UIOffsetMake(0, -1)], 
UITextAttributeTextShadowOffset, 
[UIFont fontWithName:@"STHeitiSC-Light" size:0.0], 
UITextAttributeFont, nil]]; 
+0

No establezca el tamaño 0 en su fuente, que causará errores visuales cuando presione hacia un controlador de vista. Primero, cuando presione la fuente, tendrá el tamaño 0 y luego se ajustará correctamente, pero seguirá estando visible y molesto. Configúrelo en 18.0 –

0

No se olvide de agregar la fuente a su destino.

Hice todo lo que se puede hacer sobre una fuente y no pude cargarla, cuando, de hecho, la fuente no era miembro de mi destino.

Consulte la Membresía de destino también en la fuente personalizada agregada.

1

El enlace siguiente le ayudará. Depende de dónde le gustaría establecer propiedades de fuente en la barra de navegación actual de viewController todo en cualquier lugar de la aplicación

se puede encontrar buen tutorial aquí% http://www.appcoda.com/customize-navigation-status-bar-ios-7/?utm_campaign=iOS_Dev_Weekly_Issue_118&utm_medium=email&utm_source=iOS%2BDev%2BWeekly

La idea básica es crear instancia NSDictionary y llenarlo con su fuente deseada y otras propiedades. he terminado con esta solución:

en su método de controlador -viewDidLoad después de [SUPER viewDidLoad] poner estas líneas:

UIColor *color = [UIColor redColor]; 
NSShadow *shadow = [NSShadow new]; 
UIFont *font = [UIFont fontWithName:@"EnterYourFontName" size:20.0] 
shadow.shadowColor = [UIColor greenColor]; 
shadow.shadowBlurRadius = 2; 
shadow.shadowOffset = CGSizeMake(1.0f, 1.0f); 

//fill this dictionary with text attributes 
NSMutableDictionary *topBarTextAttributes = [NSMutableDictionary new]; 
    //ios 7 
topBarTextAttributes[NSForegroundColorAttributeName] = color; 
    //ios 6 
topBarTextAttributes[UITextAttributeTextColor] = color; 
    //ios 6 
topBarTextAttributes[UITextAttributeTextShadowOffset] = [NSValue valueWithCGSize:shadow.shadowOffset]; 
topBarTextAttributes[UITextAttributeTextShadowColor] = shadow.shadowColor; 
    //ios 7 
topBarTextAttributes[NSShadowAttributeName] = shadow; 
    //ios 6 
topBarTextAttributes[UITextAttributeFont] = font; 
    //ios 7 
topBarTextAttributes[NSFontAttributeName] = font; 

//for all the controllers uncomment this line 
// [[UINavigationBar appearance]setTitleTextAttributes:topBarTextAttributes]; 

//for current controller uncoment this line 
// self.navigationController.navigationBar.titleTextAttributes = topBarTextAttributes; 
4

En iOS8 rápido, utilizar el siguiente código para establecer la fuente:

var navigationBarAppearance = UINavigationBar.appearance() 
let font = UIFont(name: "Open Sans", size: 17) 
if let font = font { 
    navigationBarAppearance.titleTextAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.whiteColor()] 
} 
Cuestiones relacionadas