Cómo centrar un UILabel en UIView


¿Cómo puedo centrar el UILabel en el UIView? Estoy usando el siguiente código

float width = weatherView.bounds.size.width; 
float height = weatherView.bounds.size.height; 

[self.label setFrame:CGRectMake(width-100,height-100, 100, 100)];
Author: highlycaffeinated, 2011-07-20

7 answers

Qué tal:

[self.label setCenter:view.center];
 102
Author: PengOne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-07 11:46:52

Si la etiqueta es un subview of view:

[self.label setCenter:CGPointMake(view.frame.size.width / 2, view.frame.size.height / 2)]

No use view.center a menos que la etiqueta y la vista tengan la misma vista superior.

Si no hay conexión inmediata, entonces tendrá que transformar el centro de la vista al espacio de coordenadas del padre de la etiqueta. Entonces podrías usar la respuesta de PengOne con el punto transformado.

 34
Author: Nashenas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-11 00:38:35

Use NSTextAlignmentCenter si lo que tiene es la etiqueta ya establecida y desea centrar su contenido.

cell.menuLabel.textAlignment = NSTextAlignmentCenter;
 18
Author: Alex Delgado,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-10 15:35:08

Una mejor solución posible es:

Primero: Si está haciendo esto programáticamente, necesitará inicializar con frame y algunas personalizaciones:

// Simple example
int yPosition = 10;
UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0, yPosition, self.view.frame.size.width, 0)];
[label setText: @"Testing..."];
[label setBackgroundColor: [UIColor clearColor]];
[label setNumberOfLines: 0];
[label sizeToFit];

Segundo: Si una etiqueta lo que está tratando de centrar puede ejecutar esto después de setNumberOflines selector llamado y 0 value asignado, su texto tendrá todas las líneas necesarias, y sizeToFit método llamado para tener una buena personalización, y finalmente:

[self.label setCenter: CGPointMake(self.view.center.x, self.label.center.y)];

Esto se centrará only the X axis, y el Y axis permanecerá como usted desea en la inicialización del marco.

PS: También es válido si no es un UILabel pero depende del control que esté utilizando necesitará otra personalización simple o ninguna, y si solo desea centrar programáticamente pero interface builder diseñado, solo necesita ejecutar el second code.

 16
Author: rokimoki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-11 13:49:58

Algo como esto debería hacer el truco... Asegúrese de que su etiqueta esté configurada para tener una alineación centrada y sea lo suficientemente grande/ancha para manejar su cadena de texto.

float viewWidth = weatherView.frame.size.width;
float viewHeight = weatherView.frame.size.height;
float labelWidth = label.frame.size.width;
float labelHeight = label.frame.size.height;

float xpos = (viewWidth/2.0f) - (labelWidth/2.0f);
float ypos = (viewHeight/2.0f) - (labelHeight/2.0f);

[label setFrame:CGRectMake(xpos,ypos,labelWidth,labelHeight)];

Creo que eso debería hacer lo que estás pidiendo.

 2
Author: Richard Baxter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-19 20:44:25

Hay dos posibilidades si su UILabel se agrega a través.xib o añadido mediante programación .

Si el primer caso es decir, añadido via .xib luego puede establecer la posición desde la pestaña inspector de tamaño de archivo xib con la propiedad' Arrange '

Y si el segundo caso persiste, puede establecer como --- [self.label setCenter: vista.centro];

 2
Author: Nijar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-30 09:53:31

La respuesta de PengOne / Alex Lockwood es simple y útil. Si tiene la intención de apoyar la rotación, agregue lo siguiente para mantenerla centrada:

[self.myLabel setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
 2
Author: DenVog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-26 15:26:18