2012-06-16 17 views
5

He añadido un tableView y arrastrado una celda de vista de tabla en él. en el panel de utilidades, cambié el estilo a subtítulo. También he intentado cambiar en el código: alineacióniOS - Alineación de texto UITableViewCell

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    cell.textLabel.textAlignment = UITextAlignmentCenter; 
    cell.detailTextLabel.textAlignment = UITextAlignmentCenter; 

    cell.textLabel.text = [myArray objectAtIndex:indexPath.row]; 
    cell.detailTextLabel.text = [myArray2 objectAtIndex:indexPath.row]; 

    return cell; 

El centro no funciona!

He intentado agregar un objeto de etiqueta a la celda para tener una solución. Pero no sé cómo acceder a él. aunque le asigné una toma de corriente, esto no funcionaría:

cell.labelForCell.... 

¿Qué debo hacer? alguna sugerencia sobre cómo hacer que funcione de la manera habitual, sin agregar una etiqueta a la celda o algo así?

+0

Solo un fyi, use NSTextAlignmentCenter. UITextAlignmentCenter está en desuso. – Viper

Respuesta

18

Para la alineación UITableViewCellStyleSubtitle texto no se puede cambiar Usted tendrá que poner una etiqueta y añadir su alineación a ella, Para ello se puede utilizar el código

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    UILabel *myLabel; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 

     myLabel = [[UILabel alloc] initWithFrame:Your_Frame]; 
     //Add a tag to it in order to find it later 
     myLabel.tag = 111; 
     //Align it 
     myLabel.textAlignment= UITextAlignmentCenter; 

     [cell.contentView addSubview:myLabel]; 
    } 

    myLabel = (UILabel*)[cell.contentView viewWithTag:111]; 
    //Add text to it 
    myLabel.text = [myArray objectAtIndex:indexPath.row]; 

    return cell; 
} 
+0

Gracias, buena pequeña referencia. – Morkrom

+0

Tenga en cuenta que 'UITextAlignment' está en desuso desde iOS6. Use 'NSTextAlignment' en su lugar. –

0

Creo que la razón es que: El ancho de la etiqueta de texto depende de la longitud del texto, si el texto es demasiado largo para mostrar todo en una línea de señal, y ya ha establecido el modo de salto de línea y establece el número de líneas en 0, encontrará que la alineación del texto será trabajo.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *identifier = @"identifier"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; 
    if (nil == cell) 
    { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier] autorelease]; 
     cell.textLabel.textAlignment = UITextAlignmentLeft; 
     cell.textLabel.textColor = [UIColor redColor]; 
     cell.detailTextLabel.textColor = [UIColor greenColor]; 
     cell.detailTextLabel.textAlignment = UITextAlignmentCenter; 
     cell.textLabel.lineBreakMode = UILineBreakModeTailTruncation; 
     cell.textLabel.numberOfLines = 0; 
    } 
    cell.textLabel.text = [NSString stringWithFormat:@"You can initialize a very long string for the textLabel, or you can set the font to be a large number to make sure that the text cann't be shown in a singal line totally:%d", indexPath.row]; 
    return cell; 

}

+0

no, el texto fue muy corto. Lo estaba probando con números. – Milad

1

El problema con el estilo de subtítulo es que hace un [self.textLabel sizeToFit] cuando se expone. Cuando se centra en un contenedor que tiene el tamaño perfecto de los contenidos, nada cambia.

Pruebe esto. En una subclase de UITableViewCell, establecer su TextAlignment, y utilizar esto como su código layoutSubviews:

- (void)layoutSubviews 
{ 
    [super layoutSubviews]; 

    { 
     CGRect frame = self.textLabel.frame; 
     frame.size.width = CGRectGetWidth(self.frame); 
     frame.origin.x = 0.0; 
     self.textLabel.frame = frame; 
    } 

    { 
     CGRect frame = self.detailTextLabel.frame; 
     frame.size.width = CGRectGetWidth(self.frame); 
     frame.origin.x = 0.0; 
     self.detailTextLabel.frame = frame; 
    } 
} 

Esto hace que el marco de ancho total de la textLabel, y por lo tanto permite que el efecto de centrado se note.

Nota: ya que esto anula las vistas de diseño, hay un costo de rendimiento, ya que se llamará con frecuencia.

+0

Buena solución simple – Drakes

0

Creo que ajustar el marco funcionará. Tenía el estilo de UITableViewCellStyleValue2, pero si tengo un texto muy largo en textLabel, se trunca al final y textAlignment no funciona aquí, así que pensé en aumentar el ancho del textoLabel.

-(void)layoutSubviews{ 
     [super layoutSubviews]; 

     if ([self.reuseIdentifier isEqualToString:@"FooterCell"]) { 
      CGRect aTframe = self.textLabel.frame; 
      aTframe.size.width += 40; 
      self.textLabel.frame = aTframe; 

      CGRect adTframe = self.detailTextLabel.frame; 
      adTframe.origin.x += 70; 
      self.detailTextLabel.frame = adTframe;   
     } 
    } 
0

Es imposible cambiar el marco para textLabel y detailTextLabel en UITableViewCell justo en cellForRowAtIndexPath: método.

Si no desea subclase su celular se puede implementar un pequeño truco usando

performSelector:withObject:afterDelay: 

con retardo cero para cambiar la geometría justo después layoutSubviews defecto:

[self performSelector:@selector(alignText:) withObject:cell afterDelay:0.0]; 

Ver Detalles en here

1

Hola, por favor agregue lo siguiente en lugar de su código,

cell.textLabel.textAlignment = UITextAlignmentCenter; 
cell.detailTextLabel.textAlignment = UITextAlignmentCenter; 

cambio a

cell.textLabel.textAlignment = NSTextAlignmentCenter; 
cell.detailTextLabel.textAlignment = NSTextAlignmentCenter; 

que va a funcionar bien.

+4

Lo siento, pero esta respuesta es incorrecta. – aqua

+0

bien, si es correcto significa aceptar mi respuesta. –

Cuestiones relacionadas