item bar iphone objective-c cocoa-touch ipad uinavigationitem

iphone - bar - UINavigationItem titleView position



navigationbar swift (7)

En lugar de initWithFrame simplemente use init y ponga [self.headerLabel sizeToFit] después de su última línea de código.

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:

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 barra izquierda. El resultado es esto:

texto alternativo http://cl.ly/41164eec656c96e7c913/content

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


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)]; }


Si convierte a headerLabel en una subvista de titleView, puede establecer el marco de headerLabel para controlar a dónde va dentro de titleView.

La forma en que lo haces ahora, no tienes ese control. Creo que el sistema operativo elige el marco de titleView basado en el espacio disponible.

¡Espero que esto ayude!


Simplemente calcule el tamaño de fotograma exacto necesario y alinéelo 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;


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]]; }


Utilicé etiquetas de título personalizadas para mis barras de navegación en todas las aplicaciones que tengo en la tienda de aplicaciones. He probado muchas formas diferentes de hacerlo y, de lejos, 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 advertencia a este enfoque es que su título puede fluir sobre la parte superior de cualquier botón que tenga en la barra de navegación si no tiene cuidado y establece que el título sea 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.


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];