iPhone OS 2.2.1, UITableViewCell and UITextAlignmentCenter
As of OS 2.2 there was a problem with UITextAlignmentCenter and UITableViewCells where the text would always show left aligned. The easiest solution was to compile your application for OS 2.0, if you weren’t using any new API features, in which case the original behaviour continued to work. However as of OS 2.2.1 it appears that this no longer works! There were some proposed solutions but they also don’t appear to work anymore.
I’d like to continue building my application for OS 2.0 compatibility so I don’t unnecessarily inconvenience users who haven’t upgraded yet, so I built the following solution that you may find useful – a UITableViewCell subclass that centres the text itself and works when your application is compiled for OS 2.0 or 2.2.1 (and probably others in between).
@interface MyButtonTableViewCell : UITableViewCell
{
}
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString*)reuseIdentifier;
@end
@implementation MyButtonTableViewCell
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString*)reuseIdentifier
{
if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
self.textAlignment = UITextAlignmentCenter;
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)adjustLabelSize
{
/* Center the label view. This works around a bug in OS 2.2 which now effects even code compiled for OS 2.0.
* When compiled for OS 2.2.1 this code is unnecessary but still works.
*/
NSArray *subviews = self.contentView.subviews;
if ([subviews count] > 0) {
unsigned int i, c = [subviews count];
for (i = 0; i < c; i++) {
UIView *subview = [subviews objectAtIndex:i];
if ([subview isKindOfClass:[UILabel class]]) {
CGRect frame = subview.frame;
frame.origin.x = floorf(self.contentView.frame.size.width / 2 - frame.size.width / 2);
subview.frame = frame;
}
}
}
}
- (void)layoutSubviews
{
[super layoutSubviews];
[self adjustLabelSize];
}
@end