2010-06-26 11 views
14

Estoy usando la propiedad titleView de UINavigationItem para establecer un UILabel personalizado con el tamaño/color de fuente que desee. Aquí está mi código:UINavigationItem titleView position

self.headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 400.0, 44.0)]; 
self.headerLabel.textAlignment = UITextAlignmentCenter; 
self.headerLabel.backgroundColor = [UIColor clearColor]; 
self.headerLabel.font = [UIFont boldSystemFontOfSize:20.0]; 
self.headerLabel.textColor = [UIColor colorWithRed:0.259 green:0.280 blue:0.312 alpha:1.0]; 
self.navigationItem.titleView = self.headerLabel; 

En la barra de navegación, también tengo un botón de la barra izquierda. El resultado es este:

alt text http://cl.ly/41164eec656c96e7c913/content

Como se puede ver, el texto no está bien centrado. Intenté establecer el origen x de la etiqueta, pero esto no tiene ningún efecto.

+0

veo ninguna imagen ... – turingtested

Respuesta

15

Si hace que headerLabel sea una subvista de titleView, puede establecer el marco de headerLabel para controlar el lugar al que va dentro de titleView.

La forma en que lo está haciendo ahora, no tiene ese control. Creo que el sistema operativo elige el marco de titleView basado en el espacio disponible.

Espero que esto ayude!

+0

Hey, he intentado esto pero mi titleview se está poniendo empujar hacia abajo un poco cuando tengo un botón a la izquierda oa la derecha. ¿Pudiste evitar que esto sucediera? – quantumpotato

+0

Mi titleView no se muestra haciendo esto ... – sebrock

+0

Esto tampoco me funciona, ¿qué estoy haciendo mal aquí? El headerLabel no aparece en absoluto cuando lo hago [self.navigationItem.titleView addSubview: headerLabel] ;. ¿Debo configurar el titleView primero? –

1

Sólo calcular el tamaño exacto necesario marco y alinear a la izquierda:

UIFont* font = [UIFont fontWithName:@"Bitsumishi" size:20]; 
CGSize maximumLabelSize = CGSizeMake(296,9999); 
CGSize expectedLabelSize = [title sizeWithFont:font constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeCharacterWrap]; 
CGRect frame = CGRectMake(0, 0, expectedLabelSize.width, expectedLabelSize.height); 
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease]; 
label.font = font; 
label.textAlignment = UITextAlignmentLeft; 
label.text = title; 
self.titleView = label; 
0
UIView *vw = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)]; 
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 40)]; 
lbl.text = @"Home"; 
lbl.textAlignment = UITextAlignmentCenter; 
lbl.backgroundColor = [UIColor clearColor]; 
lbl.textColor = [UIColor whiteColor]; 
lbl.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:20]; 
lbl.shadowColor = [UIColor blackColor]; 
lbl.shadowOffset = CGSizeMake(0,1); 
self.navigationItem.titleView = vw; 
[self.navigationItem.titleView addSubview:lbl]; 
19

En lugar de initWithFrame sólo tiene que utilizar init y poner [self.headerLabel sizeToFit] después de su última línea de código.

+2

Esto funciona como un encanto. Nadie debería haber votado por esto. –

+0

No lo voté, pero puedo ver cómo alguien podría argumentar que no responde la pregunta, pero ofrece un truco tangencial útil. – Olie

3

He usado etiquetas de título personalizadas para mis barras de navegación en cada aplicación que tengo en la tienda de aplicaciones. He probado muchas formas diferentes de hacerlo y por ahora la manera más fácil de usar una etiqueta personalizada en una barra de navegación es ignorar por completo titleView e insertar su etiqueta directamente en navigationController.view.

Con este enfoque, es fácil que el marco de la etiqueta del título siempre coincida con el marco de la barra de navegación, incluso si está utilizando una barra de navegación personalizada con un tamaño no estándar.

- (void)viewDidLoad { 
    [self.navigationController.view addSubview:self.titleLabel]; 
    [super viewDidLoad]; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation: 
      (UIInterfaceOrientation)interfaceOrientation { 
    return YES; 
} 

- (void)didRotateFromInterfaceOrientation: 
      (UIInterfaceOrientation)fromInterfaceOrientation { 
    [self frameTitleLabel]; 
} 

- (UILabel *) titleLabel { 
    if (!titleLabel) { 
     titleLabel = [[UILabel alloc]   
      initWithFrame:self.navigationController.navigationBar.frame]; 

     titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:18]; 
     titleLabel.text = NSLocalizedString(@"Custom Title", nil); 
     titleLabel.textAlignment = UITextAlignmentCenter; 
     titleLabel.lineBreakMode = UILineBreakModeTailTruncation; 
    } 
    return titleLabel; 
} 

- (void) frameTitleLabel { 
    self.titleLabel.frame = self.navigationController.navigationBar.frame; 
} 

La única salvedad a este enfoque es que su título puede fluir sobre la parte superior de los botones que tiene en la barra de navegación, si no se tiene cuidado y establecer el título a ser demasiado largo. Pero, IMO, eso es mucho menos problemático de tratar que 1) El título no se centra correctamente cuando tienes un BarButton derecho o 2) El título no aparece si tienes unBarButton izquierdo.

+1

Gracias por el comentario. Como nota, cuando implementé su enfoque, la vista creada no desapareció al presionar el botón Atrás. –

3

Tengo el mismo problema; De alguna manera, resolví este problema calculando la longitud del título y estableciendo el ancho del marco de la etiqueta en consecuencia. Aunque este no es perfecto, pero puede ser manejable. Aquí está el código.

label = [[UILabel alloc] init]; 
label.backgroundColor = [UIColor clearColor]; 
label.font = [ UIFont fontWithName: @"XXII DIRTY-ARMY" size: 32.0 ]; 
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.0f]; 
label.textAlignment = UITextAlignmentCenter; 
label.textColor =[UIColor orangeColor]; 
//label.text=categoryTitle; 
CGFloat verticalOffset = 2; 
NSString *reqSysVer = @"5.0"; 
NSString *currSysVer = [[UIDevice currentDevice] systemVersion]; 
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)   
{ 
    if (categoryTitle.length > 8) 
    { 
    label.frame = CGRectMake(0, 0, 300, 44); 
    }else { 
     label.frame = CGRectMake(0, 0, 80, 44); 
    } 

    self.navigationItem.titleView = label; 
    self.navigationItem.title=label.text; 
    [[UINavigationBar appearance] setTitleVerticalPositionAdjustment:verticalOffset forBarMetrics:UIBarMetricsDefault]; 
    [[UIBarButtonItem appearance] setTintColor:[UIColor newBrownLight]]; 


} 
0

Lo que funcionó para mí fue actualizar el marco titleView en el método viewDidAppear.

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 

    UIView *titleView = self.navigationItem.titleView; 
    CGRect navBarFrame = self.navigationController.navigationBar.frame; 
    [titleView setFrame:CGRectMake((CGRectGetWidth(navBarFrame) - TitleWidth)/2, (CGRectGetHeight(navBarFrame) - TitleHeight)/2, TitleWidth, TitleHeight)]; 
} 
Cuestiones relacionadas