titulos texto poner para insertar fondo editar creditos como iphone uinavigationcontroller resize uinavigationbar autoresize

iphone - texto - Cómo cambiar el tamaño del título en una barra de navegación de forma dinámica



editar titulos imovie (6)

Tengo algunas vistas que aparecen en un controlador de navegación. Dos de estas vistas tienen un título más largo para la barra de navegación.

El problema es que cuando el título es demasiado largo para ajustarse, algunos caracteres se truncan y se agrega "...".

¿Hay alguna forma en que pueda indicar a la barra de navegación que redimensione automáticamente el texto del título para que se ajuste?


Aquí hay un ejemplo en Swift que también permite múltiples líneas. Usando PureLayout para simplificar el diseño automático.

override func viewDidLoad() { super.viewDidLoad() configureTitleView() } func configureTitleView() { let titleLabel = UILabel() titleLabel.numberOfLines = 0 titleLabel.textAlignment = .Center titleLabel.font = UIFont.boldSystemFontOfSize(17.0) titleLabel.text = searchLoc.mapItem.name navigationItem.titleView = titleLabel titleLabel.autoPinEdgesToSuperviewMargins() // PureLayout method titleLabel.adjustsFontSizeToFitWidth = true }

Y un ejemplo de uso:


En caso de que haya agregado una vista a titleView y desee cambiar el tamaño de la vista, puede usar este código (Swift 3) :

self.translatesAutoresizingMaskIntoConstraints = false self.layoutIfNeeded() self.sizeToFit() self.translatesAutoresizingMaskIntoConstraints = true


Ninguna de las soluciones anteriores puede trabajar de forma confiable para mí. Sin embargo, encontré una solución al utilizar diferentes elementos de las respuestas proporcionadas, está en Swift 2 y es realmente elegante, ya que no requiere ningún código personalizado cada vez que cambias la etiqueta, solo usa observadores de propiedades en el título.

Tenga en cuenta que, en mi caso, tenía un botón Atrás en el lado izquierdo de la barra de navegación, que colocaba el texto fuera del centro de la pantalla, para solucionar este problema, estoy usando el texto atribuido y el indicador de cola. Todos los comentarios / información en el siguiente código:

class VCHowToTopic : UIViewController { //add handlers so that any manipulation of the title is caught and transferred to the custom drawn UILabel override var title : String? { set { super.title = newValue configureTitleView() } get { return super.title } } //MARK: - lifecycle func configureTitleView() { //some large number that makes the navigationbar schrink down our view when added let someVeryLargeNumber = CGFloat(4096) //create our label let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: someVeryLargeNumber, height: someVeryLargeNumber)) //0 means unlimited number of lines titleLabel.numberOfLines = 0 //define style of the text (we will be using attributed text) let style = NSMutableParagraphStyle() style.alignment = .Center //top compensate for the backbutton which moves the centered text to the right side of the screen //we introduce a negative tail indent, the number of 56 has been experimentally defined and might //depend on the size of your custom back button (if you have one), mine is 22x22 px style.tailIndent = -56 //create attributed text also with the right color let attrText = NSAttributedString(string: title!, attributes: [NSParagraphStyleAttributeName : style, NSForegroundColorAttributeName : UIColor.whiteColor()]) //configure the label to use the attributed text titleLabel.attributedText = attrText //add it as the titleview navigationItem.titleView = titleLabel } }


Utiliza el siguiente código en ViewDidload.

C objetivo

self.title = @"Your TiTle Text"; UILabel* tlabel=[[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 40)]; tlabel.text=self.navigationItem.title; tlabel.textColor=[UIColor whiteColor]; tlabel.font = [UIFont fontWithName:@"Helvetica-Bold" size: 30.0]; tlabel.backgroundColor =[UIColor clearColor]; tlabel.adjustsFontSizeToFitWidth=YES; tlabel.textAlignment = NSTextAlignmentCenter; self.navigationItem.titleView=tlabel;

Versión rápida

self.title = "Your TiTle Text" let tlabel = UILabel(frame: CGRectMake(0, 0, 200, 40)) tlabel.text = self.title tlabel.textColor = UIColor.whiteColor() tlabel.font = UIFont(name: "Helvetica-Bold", size: 30.0) tlabel.backgroundColor = UIColor.clearColor() tlabel.adjustsFontSizeToFitWidth = true tlabel.textAlignment = .center; self.navigationItem.titleView = tlabel

Espero que funcione para ti. Gracias


Versión rápida de respuesta aceptada + poniendo el texto de la etiqueta en el centro:

Swift 2.3:

self.title = "Your TiTle Text" 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

Y Swift 3:

self.title = "Your TiTle Text" let frame = CGRect(x: 0, y: 0, width: 200, height: 40) let tlabel = UILabel(frame: frame) tlabel.text = self.title tlabel.textColor = UIColor.white tlabel.font = UIFont.boldSystemFont(ofSize: 17) //UIFont(name: "Helvetica", size: 17.0) tlabel.backgroundColor = UIColor.clear tlabel.adjustsFontSizeToFitWidth = true tlabel.textAlignment = .center self.navigationItem.titleView = tlabel


necesita personalizar la vista del título de la barra de navegación con uilabel y proporcionar ajustar el tamaño de la fuente.

[self.navigationItem setTitleView:<"Include any UI View subclass">];