Подтвердить что ты не робот

Центр Выравнивание текста в проблеме UITableViewCell

Я новичок в разработке Objective-C и iPhone, и я столкнулся с проблемой при попытке центрировать текст в ячейке таблицы. Я искал google, но решения для старой ошибки SDK были исправлены, и они не работают для меня.

Некоторые коды:

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

Вышеупомянутый не центрирует текст.

Я также попробовал метод willDisplayCell:

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

и я пробовал некоторые из старых размещенных решений:

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

Ни одно из них не влияет на выравнивание текста. Я исчерпал идею, что любая помощь была бы наиболее оценена.

Приветствия заранее.

4b9b3361

Ответ 1

Не знаю, помогает ли ваша конкретная проблема, однако UITextAlignmentCenter работает, если вы используете initWithStyle:UITableViewCellStyleDefault

Ответ 2

Это не работает, потому что textLabel является настолько широким, насколько это необходимо для любого заданного текста. (UITableViewCell перемещает метки вокруг, поскольку он считает нужным при установке стиля UITableViewCellStyleSubtitle)

Вы можете переопределить layoutSubviews, чтобы метки всегда заполняли всю ширину ячейки.

- (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);
}

Не забудьте сохранить высоту/y-позицию одинаковой, поскольку до тех пор, пока текст detailTextLabel пуст textLabel будет вертикально центрирован.

Ответ 3

Используйте этот код:

cell.textLabel.textAlignment = NSTextAlignmentCenter;

Над кодом будет работать. Не используйте UITextAlignmentCenter, он устарел.

Ответ 4

Этот хак будет центрировать текст при использовании UITableViewCellStyleSubtitle. Загрузите обе текстовые метки своими строками, затем сделайте это, прежде чем возвращать ячейку. Может быть проще просто добавить свои собственные UILabels в каждую ячейку, но я решил найти другой способ...

// 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
}

Ответ 5

В 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);

}

В таблице методов:

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

При необходимости одно и то же можно повторить для self.detailTextLabel

Ответ 6

В той же ситуации я создал пользовательский UITableViewCell с пользовательской меткой:

Файл MCCenterTextCell.h:

#import <UIKit/UIKit.h>

@interface MCCenterTextCell : UITableViewCell

@property (nonatomic, strong) UILabel *mainLabel;

@end

Файл MCCenterTextCell.m:

 #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

Ответ 7

Вы можете использовать код для центра текста

cell.indentationLevel = 1;

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

Ответ 8

Если вы хотите выровнять текст вправо, я успешно адаптировал описанное решение здесь.

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

Ответ 9

Вот что у меня работает...

NSString *text = @"some text";
CGSize size = [text sizeWithAttributes:@{NSFontAttributeName:SOME_UIFONT}];

[cell setIndentationLevel:1];
[cell setIndentationWidth:(tableView.frame.size.width - size.width)/2.0f];

cell.textLabel.font = SOME_UIFONT;
[cell.textLabel setText:text];