在UITableViewCell问题中居中对齐文本

时间:2022-02-09 10:45:09

I'm kinda new to Objective-C and iPhone development and I've come across a problem when trying to center the text in a table cell. I've searched google but the solutions are for an old SDK bug that has been fixed and these don't work for me.

我对Objective-C和iPhone开发有点陌生,当我试图将文本居中到表格单元时遇到了一个问题。我已经搜索了谷歌,但是解决方案是针对一个旧的SDK bug,它已经被修复了,这些对我来说并不适用。

Some code:

一些代码:

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

The above doesn't center the text.

上面的文字没有居中。

I have also tried the willDisplayCell method:

我也尝试过willDisplayCell方法:

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

and I've tried some of the old posted solutions:

我尝试了一些旧的解决方案:

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

None of these have any effect on the text alignment. I have run out of idea's any help would be most appreciated.

这些对文本对齐没有任何影响。我已经没有主意了,非常感谢你的帮助。

Cheers in advance.

提前欢呼。

8 个解决方案

#1


122  

Don't know if it helps your specific problem, however UITextAlignmentCenter does work if you use initWithStyle:UITableViewCellStyleDefault

不知道它是否能帮助您解决特定的问题,但是如果您使用initWithStyle:UITableViewCellStyleDefault, UITextAlignmentCenter确实可以工作

#2


15  

It doesn't work because the textLabel is only as wide as it needs to be for any given text. (UITableViewCell moves the labels around as it sees fit when set to the UITableViewCellStyleSubtitle style)

它不起作用,因为textLabel只有任何给定文本所需的宽度。(UITableViewCell在将标签设置为UITableViewCellStyleSubtitle样式时,会根据需要移动标签)

You can override layoutSubviews to make sure the labels always fill the cell's entire width.

您可以覆盖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);
}

Be sure to keep the height/y-position the same, because as long as the detailTextLabel's text is empty textLabel will be vertically centered.

请确保高度/y位置保持不变,因为只要detailTextLabel的文本为空,textLabel就会垂直居中。

#3


4  

This hack will center the text when using UITableViewCellStyleSubtitle. Load both text labels with your strings, then do this before returning the cell. It might be simpler to just add your own UILabels to each cell, but I was determined to find another way...

当使用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
}

#4


3  

Use this code:

使用这段代码:

cell.textLabel.textAlignment = NSTextAlignmentCenter;

Above code will work. Dont use UITextAlignmentCenter, it is deprecated.

上面的代码将工作。不要使用UITextAlignmentCenter,它已被弃用。

#5


0  

In CustomTableViewCell.m:

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

}

In the method table:

方法表:

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

If needed, the same thing can be repeated for self.detailTextLabel

如果需要,可以对self.detailTextLabel重复同样的操作

#6


0  

In same situation I created custom UITableViewCell with a custom label:

在同样的情况下,我使用自定义标签创建了自定义UITableViewCell:

MCCenterTextCell.h file:

MCCenterTextCell。h文件:

#import <UIKit/UIKit.h>

@interface MCCenterTextCell : UITableViewCell

@property (nonatomic, strong) UILabel *mainLabel;

@end

MCCenterTextCell.m file:

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


0  

You could use code to center text

您可以使用代码将文本居中

cell.indentationLevel = 1;

细胞。indentationLevel = 1;

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

细胞。indentationWidth =[UIScreen mainScreen].bounds.size.width / 2 - 10;

#8


0  

In case one wish to align the text to the right, I've had success adapting the solution described here.

如果有人希望将文本与右对齐,我已经成功地修改了这里描述的解决方案。

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

#1


122  

Don't know if it helps your specific problem, however UITextAlignmentCenter does work if you use initWithStyle:UITableViewCellStyleDefault

不知道它是否能帮助您解决特定的问题,但是如果您使用initWithStyle:UITableViewCellStyleDefault, UITextAlignmentCenter确实可以工作

#2


15  

It doesn't work because the textLabel is only as wide as it needs to be for any given text. (UITableViewCell moves the labels around as it sees fit when set to the UITableViewCellStyleSubtitle style)

它不起作用,因为textLabel只有任何给定文本所需的宽度。(UITableViewCell在将标签设置为UITableViewCellStyleSubtitle样式时,会根据需要移动标签)

You can override layoutSubviews to make sure the labels always fill the cell's entire width.

您可以覆盖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);
}

Be sure to keep the height/y-position the same, because as long as the detailTextLabel's text is empty textLabel will be vertically centered.

请确保高度/y位置保持不变,因为只要detailTextLabel的文本为空,textLabel就会垂直居中。

#3


4  

This hack will center the text when using UITableViewCellStyleSubtitle. Load both text labels with your strings, then do this before returning the cell. It might be simpler to just add your own UILabels to each cell, but I was determined to find another way...

当使用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
}

#4


3  

Use this code:

使用这段代码:

cell.textLabel.textAlignment = NSTextAlignmentCenter;

Above code will work. Dont use UITextAlignmentCenter, it is deprecated.

上面的代码将工作。不要使用UITextAlignmentCenter,它已被弃用。

#5


0  

In CustomTableViewCell.m:

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

}

In the method table:

方法表:

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

If needed, the same thing can be repeated for self.detailTextLabel

如果需要,可以对self.detailTextLabel重复同样的操作

#6


0  

In same situation I created custom UITableViewCell with a custom label:

在同样的情况下,我使用自定义标签创建了自定义UITableViewCell:

MCCenterTextCell.h file:

MCCenterTextCell。h文件:

#import <UIKit/UIKit.h>

@interface MCCenterTextCell : UITableViewCell

@property (nonatomic, strong) UILabel *mainLabel;

@end

MCCenterTextCell.m file:

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


0  

You could use code to center text

您可以使用代码将文本居中

cell.indentationLevel = 1;

细胞。indentationLevel = 1;

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

细胞。indentationWidth =[UIScreen mainScreen].bounds.size.width / 2 - 10;

#8


0  

In case one wish to align the text to the right, I've had success adapting the solution described here.

如果有人希望将文本与右对齐,我已经成功地修改了这里描述的解决方案。

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