66

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.

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:

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

Magpie
  • 6,983
  • 14
  • 51
  • 67

9 Answers9

129

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

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
Philip Jespersen
  • 2,816
  • 2
  • 19
  • 9
  • 4
    This helped as I wasn't using the subtle for the cells I wanted to center. Thanks. I guess UITextAlignmentCenter doesn't work for UITableViewCellStyleSubtitle cells. – Magpie Aug 31 '10 at 16:28
  • 2
    `UITextAlignmentCenter` is now deprecated. See [this post](http://stackoverflow.com/a/12793054/2521004) for a good alternative. – Automate This Jul 11 '14 at 15:14
  • 2
    PERFECT. Someone at Apple should be fired by providing us with error messages that don't explain how to solve issues. If it was not stackoverflow and people like you, we would be all screwed. – Duck Oct 19 '14 at 19:36
  • Not the correct answer. UITextAlignmentCenter is deprecated. Use instead: cell.textLabel.textAlignment = NSTextAlignmentCenter; – joan May 26 '17 at 13:54
16

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)

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

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

voidStern
  • 3,678
  • 1
  • 29
  • 32
  • These lines combined with: `self.detailTextLabel.textAlignment = UITextAlignmentRight;` and `self.textLabel.textAlignment = UITextAlignmentRight;` Did _exactly_ what I was looking for and allowed me to continue using the UITableViewCellStyleSubtitle. – vim_commando Jul 01 '12 at 21:44
7

Use this code:

cell.textLabel.textAlignment = NSTextAlignmentCenter;

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

Tejinder
  • 1,507
  • 19
  • 22
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 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
}
Jeff
  • 2,659
  • 1
  • 22
  • 41
0

In 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

Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
Alexander
  • 9,074
  • 2
  • 15
  • 13
0

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

MCCenterTextCell.h file:

#import <UIKit/UIKit.h>

@interface MCCenterTextCell : UITableViewCell

@property (nonatomic, strong) UILabel *mainLabel;

@end

MCCenterTextCell.m file:

 #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
Denis Kutlubaev
  • 15,320
  • 6
  • 84
  • 70
0

You could use code to center text

cell.indentationLevel = 1;

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

dip
  • 129
  • 1
  • 4
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);
Community
  • 1
  • 1
Tal Aloni
  • 1,429
  • 14
  • 14
0

Here is what works for me...

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];
Peter
  • 1,061
  • 1
  • 13
  • 20