UILabel Alinear texto al centro


Respuestas:


568

Desde iOS 6 y posterior UITextAlignmentestá en desuso. utilizarNSTextAlignment

myLabel.textAlignment = NSTextAlignmentCenter;

Versión rápida de iOS 6 y posterior

myLabel.textAlignment = .center

8
la versión rápida podría simplificarse :) myLabel.textAlignment = .Center
— aryaxt

1
.center ← minúscula
— Lucas

83

Aquí hay un código de muestra que muestra cómo alinear texto usando UILabel:

label = [[UILabel alloc] initWithFrame:CGRectMake(60, 30, 200, 12)];
label.textAlignment = NSTextAlignmentCenter;

Puedes leer más sobre esto aquí UILabel


27
UITextAlignmentestá en desuso desde iOS 5. Use en su NSTextAlignmentlugar.
— Philip007

Falso, UITextAligment está en desuso. En UIStringDrawing.h (UIKit) puede encontrar este código:// Deprecated: use NSTextAlignment enum in UIKit/NSText.h typedef NS_ENUM(NSInteger, UITextAlignment) { UITextAlignmentLeft = 0, UITextAlignmentCenter, UITextAlignmentRight, // could add justified in future } NS_DEPRECATED_IOS(2_0,6_0);
— aramusss

12

Para centrar el texto en un UILabel en Swift (que está dirigido a iOS 7+) puede hacer lo siguiente:

myUILabel.textAlignment = .Center

O

myUILabel.textAlignment = NSTextAlignment.Center

8

NB: Según la referencia de clase UILabel , a partir de iOS 6 este enfoque ahora está en desuso.

Simplemente use la textAlignmentpropiedad para ver la alineación requerida usando uno de los UITextAlignmentvalores. ( UITextAlignmentLeft, UITextAlignmentCentero UITextAlignmentRight.)

p.ej: [myUILabel setTextAlignment:UITextAlignmentCenter];

Consulte la referencia de clase UILabel para obtener más información.


6

Usar yourLabel.textAlignment = NSTextAlignmentCenter;para iOS> = 6.0 y yourLabel.textAlignment = UITextAlignmentCenter;para iOS <6.0.





3

En xamarin ios, suponga que el nombre de su etiqueta es título y luego haga lo siguiente

title.TextAlignment = UITextAlignment.Center;

2
La pregunta no es sobre Xamarin. ¡Y UITextAlignmentestá en desuso en iOS 6 !
— FelixSFD

0

En Swift 4.2 y Xcode 10

let lbl = UILabel(frame: CGRect(x: 10, y: 50, width: 230, height: 21))
lbl.textAlignment = .center //For center alignment
lbl.text = "This is my label fdsjhfg sjdg dfgdfgdfjgdjfhg jdfjgdfgdf end..."
lbl.textColor = .white
lbl.backgroundColor = .lightGray//If required
lbl.font = UIFont.systemFont(ofSize: 17)

 //To display multiple lines in label
lbl.numberOfLines = 0
lbl.lineBreakMode = .byWordWrapping

lbl.sizeToFit()//If required
yourView.addSubview(lbl)
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.