2010-08-12 11 views
58

Soy un poco nuevo en el desarrollo de Objective-C y iPhone y me he encontrado con un problema al tratar de centrar el texto en una celda de tabla. He buscado en google, pero las soluciones son para un viejo error de SDK que se ha corregido y estos no funcionan para mí.Center Alinea el texto en el problema UITableViewCell

Algunos código:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

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

    cell.textLabel.text = @"Please center me"; 
    cell.textLabel.textAlignment = UITextAlignmentCenter; 
    return cell; 
} 

Lo anterior no centrar el texto.

También he probado el método willDisplayCell:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { 
    cell.textLabel.textAlignment = UITextAlignmentCenter; 
} 

y he probado algunas de las viejas soluciones publicadas:

UILabel* label = [[[cell contentView] subviews] objectAtIndex:0]; 
label.textAlignment = UITextAlignmentCenter; 
return cell; 

Ninguno de ellos tiene ningún efecto sobre la alineación del texto. Me he quedado sin idea de que cualquier ayuda sería muy apreciada.

Saludos con anticipación.

+11

UITextAlignment está en desuso en iOS 6.0, ahora es NSTextAlignment – Souljacker

Respuesta

120

No sabe si ayuda a su problema específico, sin embargo UITextAlignmentCenter no funciona si se utiliza initWithStyle:UITableViewCellStyleDefault

+4

Esto ayudó ya que no estaba usando el sutil para las células que quería centro. Gracias. Supongo que UITextAlignmentCenter no funciona para las celdas UITableViewCellStyleSubtitle. – Magpie

+2

'UITextAlignmentCenter' ahora está en desuso. Ver [esta publicación] (http://stackoverflow.com/a/12793054/2521004) para una buena alternativa. –

+2

PERFECTO. Alguien en Apple debería ser despedido proporcionándonos mensajes de error que no explican cómo resolver problemas. Si no fuera por el stackoverflow y personas como tú, estaríamos todos jodidos. – SpaceDog

4

Este truco se centrará el texto cuando se utiliza UITableViewCellStyleSubtitle. Cargue ambas etiquetas de texto con sus cadenas, luego haga esto antes de devolver la celda. Puede ser que sea más fácil de simplemente añadir sus propios UILabels a cada celda, pero yo estaba decidido a encontrar otra manera ...

// UITableViewCellStyleSubtitle measured font sizes: 18 bold, 14 normal 

UIFont *font = [UIFont boldSystemFontOfSize:18]; // measured after the cell is rendered 
CGSize size = [cell.textLabel.text sizeWithFont:font]; 
CGSize spaceSize = [@" " sizeWithFont:font]; 
float excess_width = (cell.frame.size.width - 16) - size.width; 
if (cell.textLabel.text && spaceSize.width > 0 && excess_width > 0) { // sanity 
    int spaces_needed = (excess_width/2.0)/spaceSize.width; 
    NSString *pad = [@"" stringByPaddingToLength:spaces_needed withString:@" " startingAtIndex:0]; 
    cell.textLabel.text = [pad stringByAppendingString:cell.textLabel.text]; // center the text 
} 

font = [UIFont systemFontOfSize:14]; // detail, measured 
size = [cell.detailTextLabel.text sizeWithFont:font]; 
spaceSize = [@" " sizeWithFont:font]; 
excess_width = (cell.frame.size.width - 16) - size.width; 
if (cell.detailTextLabel.text && spaceSize.width > 0 && excess_width > 0) { // sanity 
    int spaces_needed = (excess_width/2.0)/spaceSize.width; 
    NSString *pad = [@"" stringByPaddingToLength:spaces_needed withString:@" " startingAtIndex:0]; 
    cell.detailTextLabel.text = [pad stringByAppendingString:cell.detailTextLabel.text]; // center the text 
} 
+1

no funcionó para mí – marciokoko

15

que no funciona debido a que el textLabel es tan amplia como tiene que ser para cualquier texto dado (UITableViewCell mueve las etiquetas como lo considere oportuno cuando se establece en el estilo UITableViewCellStyleSubtitle)

Puede anular las vistas de diseño para asegurarse de que las etiquetas llenan siempre el ancho completo de la celda.

- (void) layoutSubviews 
{ 
    [super layoutSubviews]; 
    self.textLabel.frame = CGRectMake(0, self.textLabel.frame.origin.y, self.frame.size.width, self.textLabel.frame.size.height); 
    self.detailTextLabel.frame = CGRectMake(0, self.detailTextLabel.frame.origin.y, self.frame.size.width, self.detailTextLabel.frame.size.height); 
} 

Asegúrese de mantener la posición y la altura/el mismo, porque mientras el texto detailTextLabel 's está vacío textLabel se centrará verticalmente.

+0

Estas líneas combinadas con: 'self.detailTextLabel.textAlignment = UITextAlignmentRight;' y 'self.textLabel.textAlignment = UITextAlignmentRight;' Hicieron _exactly_ lo que estaba buscando y me permitieron seguir utilizando UITableViewCellStyleSubtitle. –

0

En CustomTableViewCell.m:

- (void)layoutSubviews { 
    [super layoutSubviews]; 

    self.textLabel.frame = CGRectMake(0, self.textLabel.frame.origin.y, self.contentView.frame.size.width, self.textLabel.frame.size.height); 

} 

En la tabla de métodos:

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

    CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
    cell = [[[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease]; 
    } 

    cell.textLabel.text = @"Title"; 
    cell.textLabel.textAlignment = UITextAlignmentCenter; 

    return cell; 
} 

Si es necesario, lo mismo se puede repetir para self.detailTextLabel

0

En misma situación que he creado a medida UITableViewCell con una etiqueta personalizada:

MCCenterText Cell.h archivo:

#import <UIKit/UIKit.h> 

@interface MCCenterTextCell : UITableViewCell 

@property (nonatomic, strong) UILabel *mainLabel; 

@end 

MCCenterTextCell.m archivo:

#import "MCCenterTextCell.h" 


@interface MCCenterTextCell() 


@end 


@implementation MCCenterTextCell 

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) { 

     self.accessoryType = UITableViewCellAccessoryNone; 
     self.selectionStyle = UITableViewCellSelectionStyleGray; 
     _mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 5, 320, 30)]; 
     _mainLabel.font = BOLD_FONT(13); 
     _mainLabel.textAlignment = NSTextAlignmentCenter; 
     [self.contentView addSubview:_mainLabel]; 

    } 
    return self; 
} 

- (void)setSelected:(BOOL)selected animated:(BOOL)animated 
{ 
    [super setSelected:selected animated:animated]; 

    // Configure the view for the selected state 
} 


@end 
3

Usar este código:

cell.textLabel.textAlignment = NSTextAlignmentCenter; 

Por encima de código funcionará. No utilice UITextAlignmentCenter, está en desuso.

+0

De hecho, esto funciona, ¡gracias! –

0

Se puede utilizar código para centrar el texto

cell.indentationLevel = 1;

cell.indentationWidth = [UIScreen mainScreen] .bounds.size.width/2-10;

0

En caso de que desee alinear el texto a la derecha, he tenido éxito en adaptar la solución descrita here.

cell.transform = CGAffineTransformMakeScale(-1.0, 1.0); 
cell.textLabel.transform = CGAffineTransformMakeScale(-1.0, 1.0); 
cell.detailTextLabel.transform = CGAffineTransformMakeScale(-1.0, 1.0); 
Cuestiones relacionadas