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.
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.
Don't know if it helps your specific problem, however UITextAlignmentCenter
does work if you use initWithStyle:UITableViewCellStyleDefault
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With