2012-03-28 12 views
7

No estoy teniendo mucha suerte centrando verticalmente la etiqueta que estoy agregando al TitleView en el UINavigationBar. Puedes ver lo que parece a continuación.Centrado de etiquetas verticalmente en UINavigationBar TitleView

Text not vertically aligned

Esta es la forma en que estoy añadiendo la etiqueta:

UILabel *titleLabel = [[UILabel alloc] init]; 
titleLabel.text = NSLocalizedString(@"activeSessionsTitle",@""); 
titleLabel.font = [Util SETTING_NEO_HEADER_FONT]; 
titleLabel.textColor = [UIColor whiteColor]; 
titleLabel.backgroundColor = [UIColor clearColor]; 
titleLabel.textAlignment = UITextAlignmentCenter; 
titleLabel.shadowColor = [UIColor colorWithRed:0.0f/255.0f green:0.0f/255.0f blue:0.0f/255.0f alpha:0.25f]; 
titleLabel.shadowOffset = CGSizeMake(0.0f, -1.0f); 
[titleLabel sizeToFit]; 

super.navigationItem.titleView = titleLabel; 

Creo que la razón por qué se hace esto es que hay algo raro con la fuente real que estoy usando - como He tenido que reposicionar mucho dentro de botones y cosas por el estilo. Pude resolver el problema en todos lados menos en la barra de navegación.

+0

Ver este post http://stackoverflow.com/a/8475788/716216 –

Respuesta

11

Terminé usando una combinación de las RPM respuesta a la izquierda y uno de los comentarios en mi pregunta. Esto es lo que finalmente lo fijó para mí:

UIView *customTitleView = [[UIView alloc] init]; 
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 3.0f, 200.0f, 30.0f)]; 
titleLabel.text = titleString; 
titleLabel.font = [Util SETTING_NEO_HEADER_FONT]; 
titleLabel.textColor = [UIColor whiteColor]; 
titleLabel.backgroundColor = [UIColor clearColor]; 
titleLabel.textAlignment = UITextAlignmentCenter; 
titleLabel.shadowColor = [UIColor colorWithRed:0.0f/255.0f green:0.0f/255.0f blue:0.0f/255.0f alpha:0.25f]; 
titleLabel.shadowOffset = CGSizeMake(0.0f, -1.0f); 
[titleLabel sizeToFit]; 

customTitleView.frame = CGRectMake(self.navigationItem.titleView.frame.size.width/2 - titleLabel.frame.size.width/2, self.navigationItem.titleView.frame.size.height/2 - titleLabel.frame.size.height/2, titleLabel.frame.size.width, titleLabel.frame.size.height); 

[customTitleView addSubview:titleLabel]; 
[titleLabel release]; 

[self.navigationItem setTitleView:customTitleView]; 
[customTitleView release]; 

Si está usando este trozo de código, puede que tenga que jugar con el valor de "Y" de la etiqueta del título initWithFrame: llamar. Lo tengo configurado en 3.0f, pero puede que tengas que ajustarlo un poco para tu propio uso.

La razón por la cual las otras soluciones no parecían funcionar para mí es que se descentraran horizontalmente dependiendo de si tenía un botón de barra (izquierda o derecha). Si no había botones de barra, estaba bien, y si había dos, estaba bien. Pero uno haría que fuera del centro.

+0

Ideal para iOS de menos de 5, pero para iOS 5 en adelante tienes la API de apariencia y no necesitas hacer esto, así que mira @ Respuesta de Moe – bandejapaisa

1

No creo que esto tenga nada que ver con su fuente. También he usado TitleView y creo que la forma en que presenta la vista de una manera extraña y no tiene en cuenta cuál es el tamaño de tu vista.

También podría establecer el marco de su vista de etiqueta como tal

titleLabel.frame = CGRectMake(self.navigationItem.titleView.frame.size.width/2 - titleLabel.frame.size.width/2, self.navigationItem.titleView.frame.size.height/2 - titleLabel.frame.size.height/2, titleLabel.frame.size.width, titleLabel.frame.size.height); 

self.navigationItem.titleView = titleLabel; 
+0

Esto no parece hacer una diferencia - A pesar de que no usamos la respuesta de una manera diferente! – Hosemeyer

+0

Ah, sí, debe agregarlo a una vista superior y asignarlo como vista de título. Lo siento, debería haberte dicho eso antes. Eso también lo sabía :( – RPM

+0

En realidad, ¿qué es titleLabel? –

28

Abriendo una pregunta anterior, pero me pareció muy útil.

iOS 5 permite que el de usar [UINavigationBar appearance] que es ideal para el cambio de título de la vista de la barra de título y sin la necesidad de un UIView personalizado:

[[UINavigationBar appearance] setTitleTextAttributes: 
     [NSDictionary dictionaryWithObjectsAndKeys: 
      [UIColor redColor], 
      UITextAttributeTextColor, 
      [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8], 
      UITextAttributeTextShadowColor, 
      [NSValue valueWithUIOffset:UIOffsetMake(0, -1)], 
      UITextAttributeTextShadowOffset, 
      [UIFont fontWithName:@"HelveticaNeue" size:25.0f], 
      UITextAttributeFont, 
      nil]]; 

A veces, dependiendo de la UIFont que se utilice, el título de la vista puede estar verticalmente apagado.

Para solucionar este problema, puede utilizar:

[self.navigationBar setTitleVerticalPositionAdjustment:(float) forBarMetrics:UIBarMetricsDefault]; 

(float) ser un valor positivo para empujar el titleview abajo, y un valor negativo para empujar el titleview arriba.

Espero que esto ayude.

+7

También puede establecer el ajuste de posición vertical utilizando el aspecto UINavigationBar, es decir: '[[UINavigationBar apariencia] setTitleVerticalPositionAdjustment: (float) forBarMetrics: UIBarMetricsDefault];' –

+2

¡acaba de salvar mi cuello, señor! ¡toma mi voto! :) – nburk

+0

De nada, nburk. :) – Moe

0
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName:UIFont(name:"Exo2-Bold", size: 18) as! AnyObject,NSForegroundColorAttributeName:UIColor.whiteColor()] 
+1

No es lo que OP estaba pidiendo. – Cesare

Cuestiones relacionadas