custom bar iphone uinavigationbar title

iphone - custom - status bar ios



centrar título personalizado en UINavigationBar? (7)

¡Buena respuesta! Sin embargo, sizeWithFont ahora está en desuso. Usted querría hacer algo como esto ahora.

NSDictionary *textTitleOptions = [NSDictionary dictionaryWithObjectsAndKeys: [UIFont fontWithName:@"Helvetica" size:30], NSFontAttributeName, nil]; CGSize requestedTitleSize = [[NSString stringWithFormat:@"Your String"] sizeWithAttributes:textTitleOptions]; CGFloat titleWidth = MIN(self.view.frame.size.width, requestedTitleSize.width); UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleWidth, 44)];

Tengo un título personalizado de UINavigationBar y un botón de retroceso personalizado. Mi problema es que el título no está centrado en el iPhone. Es como si mi botón Atrás estuviera empujando el título hacia la derecha. ¿Alguna idea de cómo puedo centrarlo?

int height = self.navigationController.navigationBar.frame.size.height; int width = self.navigationController.navigationBar.frame.size.width; UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, width + 300, 20)]; navLabel.backgroundColor = [UIColor whiteColor]; navLabel.textColor = [UIColor redColor]; navLabel.font = [UIFont fontWithName:@"Helvetica" size:30]; navLabel.textAlignment = UITextAlignmentCenter; self.navigationItem.titleView = navLabel; [navLabel release]; ((UILabel *)self.navigationItem.titleView).text = self.title;

¡Gracias!

Editar Quité el código superfluo y añadí esta imagen:

Observe cómo se desplaza el título para acomodar el botón ...


El título no está centrado en la barra de navegación. Está centrado entre los botones de la izquierda y los botones de la derecha de la barra de navegación. Esto significa que si tiene un botón grande a la izquierda, el título se desplazará a la derecha.

Puedes cambiar el centro agregando una restricción centrada a tu título y luego modificándolo para que sea realmente el centro de la barra de navegación:

// Position the title in the middle of the navbar and not in the middle of buttons fileprivate func centerTitle () { if let navigation = self.navigationController { let titleMiddle = navigation.navigationBar.convert(titleViewLabel.frame, from: titleViewLabel.superview).midX let diff = navigation.navigationBar.center.x - titleMiddle constraintTitleViewCentered.constant += diff } }


Swift 2.3:

let tlabel = UILabel(frame: CGRectMake(0, 0, 200, 40)) tlabel.text = self.title tlabel.textColor = UIColor.whiteColor() tlabel.font = UIFont.boldSystemFontOfSize(17) //UIFont(name: "Helvetica", size: 17.0) tlabel.backgroundColor = UIColor.clearColor() tlabel.adjustsFontSizeToFitWidth = true tlabel.textAlignment = .Center self.navigationItem.titleView = tlabel


Swift 3 para la respuesta de @BHuelse:

let image = UIImage(named: "logo") let logoView = UIView.init(frame: CGRect(x: 0, y: 0, width: 0, height: 30)) let imageView = UIImageView(frame: CGRect(x: -45, y: 5, width: 90, height: 20)) imageView.image = image imageView.contentMode = .scaleAspectFit logoView.addSubview(imageView) self.navigationItem.titleView = logoView


Utilicé restricciones de reproducción automática para resolver este problema:

  1. Agregue UILabel en un UIView.
  2. Establecer restricciones de centerX para la UILabel:

    self.titleLabelCenterXConstraint = [NSLayoutConstraint constraintWithItem:self.titleLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1.0f constant:0.0f];

  3. En UIView layoutSubViews para ajustar el valor de compensación centerX:

    - (void)layoutSubviews { [super layoutSubviews]; CGFloat screenCenter = CGRectGetMidX([UIScreen mainScreen].bounds); CGFloat diffCenter = screenCenter - CGRectGetMidX(self.frame); self.titleLabelCenterXConstraint.constant = diffCenter; }

  4. establecer UIView a navigationItem titleView


Yo tuve el mismo problema antes. Tenía un UINavigationbar con el UINavigationbar derecho e izquierdo. Quiero centrar una imagen en la UINavigationbar . Así que tuve que poner la imagen en una vista UIView con width 0. La imagen de la imagen obtiene un valor x que es la mitad de su propio width .

UINavigationItem *item = navigationController.topViewController.navigationItem; UIView *backView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 30)]; [img_logo setFrame:CGRectMake(-45, 5, 90, 20)]; [backView addSubview:img_logo]; item.titleView = backView;


iOS está haciendo esto porque el marco que inicializas es de hasta 300 píxeles de ancho. Está tratando de centrar el marco completo, el marco es más grande que el espacio en el que quiere encajar (debido al botón) y, por lo tanto, su etiqueta se empuja hacia la derecha. Lo que debe hacer es darle al Marco de la etiqueta de navegación el tamaño mínimo que necesita.

Entonces, si su texto solo tiene 100 píxeles de ancho, pero el marco es de 400 píxeles, entonces iOS está tratando de centrar los 400 píxeles en el encabezado de navegación y no tiene suficiente espacio. Cuando establezca el tamaño en el 100px real que se necesita, iOS centrará su encabezado correctamente, porque hay un montón de espacio para centrar 100px.

El fragmento de código a continuación debería ayudarlo a detectar el tamaño mínimo que necesita su marco, dependiendo de la fuente y el texto que intenta ingresar. Asegúrese de que el marco de la etiqueta sea lo más pequeño posible, pero no exceda el ancho máximo. (El ancho de la barra de navegación).

UIFont* titleFont = [UIFont fontWithName:@"Helvetica" size:30]; CGSize requestedTitleSize = [titleText sizeWithAttributes:@{NSFontAttributeName: titleFont}]; CGFloat titleWidth = MIN(maxTitleWidth, requestedTitleSize.width); UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, titleWidth, 20)]; navLabel.backgroundColor = [UIColor whiteColor]; navLabel.textColor = [UIColor redColor]; navLabel.font = [UIFont fontWithName:@"Helvetica" size:30]; navLabel.textAlignment = NSTextAlignmentCenter; navLabel.text = titleText; self.navigationItem.titleView = navLabel;