Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center Align text in UITableViewCell problem

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.

like image 808
Magpie Avatar asked Aug 12 '10 11:08

Magpie


People also ask

How do I center align text in Wordpress?

At first, select the text block for which you want to change the alignment. Then click on the alignment icon from the toolbar. By default, it will be left-aligned. Just select the 'Align Text Center' to center the text or 'Align text right' to place the text right.


2 Answers

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

like image 98
Philip Jespersen Avatar answered Oct 05 '22 12:10

Philip Jespersen


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.

like image 35
voidStern Avatar answered Oct 05 '22 11:10

voidStern