Center Align text in UITableViewCell problem
Solution 1:
Don't know if it helps your specific problem, however UITextAlignmentCenter
does work if you use initWithStyle:UITableViewCellStyleDefault
Solution 2:
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.
Solution 3:
Use this code:
cell.textLabel.textAlignment = NSTextAlignmentCenter;
Above code will work. Dont use UITextAlignmentCenter, it is deprecated.
Solution 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
}