Center Align text in UITableViewCell problem

Magpie picture Magpie · Aug 12, 2010 · Viewed 63.7k times · Source

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.

Answer

Philip Jespersen picture Philip Jespersen · Aug 24, 2010

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