2012-06-16 5 views
5

Я добавил tableView и перетащил в него ячейку просмотра таблицы. на панели «Утилиты», я изменил стиль на субтитры. Я также попытался изменить его в коде: выравниваниеiOS - выравнивание текста 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; 

Центр не работает!

Я попытался добавить объект метки в ячейку, чтобы иметь обходное решение. Но я не знаю, как получить к нему доступ. даже если я назначил ему выход, это не сработало бы:

cell.labelForCell.... 

Что мне делать? любые предложения о том, как я делаю это обычным способом, без добавления ярлыка в ячейку или что-то еще?

+0

Просто fyi, используйте NSTextAlignmentCenter. UITextAlignmentCenter устарел. – Viper

ответ

18

Для выравнивания UITableViewCellStyleSubtitle текста не может быть изменен Вы должны поставить метку и добавить выравнивание к нему, Для этого вы можете использовать этот код

- (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

Спасибо, милый маленький справки. – Morkrom

+0

Обратите внимание, что 'UITextAlignment' устарел с iOS6. Вместо этого используйте 'NSTextAlignment'. –

0

Я думаю, что причина в том, что: ширина textLabel зависит от длины текста, если текст слишком длинный, чтобы показать все в сигнальной строке, и вы уже установили режим разрыва строки и установили количество строк в 0, вы обнаружите, что выравнивание текста будет Работа.

- (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

нет, текст был очень коротким. Я тестировал его цифрами. – Milad

1

Проблема стиля субтитров является то, что он делает [self.textLabel sizeToFit], когда он вынимает. Когда вы центрируете контейнер, который является идеальным размером содержимого, ничего не меняется.

Попробуйте это. В подклассе UITableViewCell, установить TextAlignment, и использовать это в качестве кода 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; 
    } 
} 

Это делает кадр полную ширину TextLabel, и, таким образом, позволяет центрирующий эффект заметен.

Примечание: поскольку это переопределяет layoutSubviews, существует стоимость исполнения, так как она будет вызываться часто.

+0

Хорошее простое решение – Drakes

0

Я думаю, что настройка рамы будет работать. У меня был стиль UITableViewCellStyleValue2, но если у меня есть длинный текст в textLabel, он становится усеченным в хвосте, а textAlignment здесь не работает, поэтому мысль об увеличении ширины textLabel.

-(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

невозможно изменить рамку для TextLabel и detailTextLabel в UITableViewCell прямо в cellForRowAtIndexPath: метод.

Если вы не хотите, чтобы подклассы вашу клетку можно реализовать небольшой хак с помощью

performSelector:withObject:afterDelay: 

с нулевой задержкой для изменения геометрии сразу после по умолчанию layoutSubviews:

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

Показать детали на here

1

Привет, пожалуйста, добавьте следующее вместо кода,

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

изменение

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

он будет работать нормально.

+4

Извините, но этот ответ неверен. – aqua

+0

ok, если правильный означает принять мой ответ. –

Смежные вопросы