mohamed Ali mohamed Ali - 3 months ago 19
iOS Question

align the text in UITableViewCell to the right

I need to align the text in the cell to right.

but even when i set to right the text is align to left as show in the screen shot
any idea why is this strange behaviour of the cell

cell.textLabel.textAlignment = NSTextAlignmentRight;
cell.detailTextLabel.textAlignment = NSTextAlignmentRight;


After reading related questions and answers on stackoverflow I could not find one solving my problem

enter image description here

Answer

The only solution to solve this problem is to create custuom cell first create MTTableViewCell.h


#import <UIKit/UIKit.h>

@interface MTTableViewCell : UITableViewCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;
@end

then create MTTableViewCell.m


#import "MTTableViewCell.h"

@implementation MTTableViewCell


- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Initialization code
}
return self;
}


- (void) layoutSubviews {
[super layoutSubviews];
//self.textLabel.frame = CGRectMake(200, 0, 310, 20);
self.detailTextLabel.textAlignment = NSTextAlignmentRight;
self.textLabel.textAlignment = NSTextAlignmentRight;

//self.textLabel.frame = CGRectMake(100, 0, 310, 20);
CGRect adjustedFrame = self.textLabel.frame;
adjustedFrame.origin.x -= 10.0f;
self.textLabel.frame = adjustedFrame;
adjustedFrame = self.detailTextLabel.frame;
adjustedFrame.origin.x -= 10.0f;
self.detailTextLabel.frame = adjustedFrame;


{
CGRect frame = self.textLabel.frame;
frame.size.width = CGRectGetWidth(self.frame);

if(self.accessoryView != nil){
if ( IDIOM == IPAD ) {
frame.size.width = frame.size.width - 210;
} else {
frame.size.width = frame.size.width - 120;
}

frame.origin.x +=30;
}
else{
frame.size.width = frame.size.width - 50;
frame.origin.x += 30.0;
}
self.textLabel.frame = frame;
}

{
CGRect frame = self.detailTextLabel.frame;
frame.size.width = CGRectGetWidth(self.frame);

if(self.accessoryView != nil){
if ( IDIOM == IPAD ) {
frame.size.width = frame.size.width - 210;
} else {
frame.size.width = frame.size.width - 120;
}
frame.origin.x += 30.0;
}
else{
frame.size.width = frame.size.width - 50;
frame.origin.x += 30.0;
}
self.detailTextLabel.frame = frame;
}


}

@end

then in your cell

cell = [[[MTTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
[cell.textLabel setNumberOfLines:2];
[cell.detailTextLabel setNumberOfLines:3];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];

that is