vadim
vadim

Reputation: 119

Problems aligning text with UITableViewCell

I have a normal cell in tableView, when I want to align it text to right I use:

if (cell == nil) {
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];        
     cell.textLabel.textAlignment = UITextAlignmentRight;           
}

But now I want to use the UITableViewCell for displaying also detailTextLabel I tried to align it to right again but nothing happens:

if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.textAlignment = UITextAlignmentRight;
    cell.detailTextLabel.textAlignment = UITextAlignmentRight;    
}

Upvotes: 0

Views: 3938

Answers (4)

malex
malex

Reputation: 10096

It is impossible to change frame for textLabel and detailTextLabel in UITableViewCellStyleSubtitle table cell in a simple way.

It is better to subclass your cell to make custom layout. But also you can implement a small hack using

performSelector:withObject:afterDelay:

with zero delay for changing textLabel frame right after layoutSubviews:

[self performSelector:@selector(alignText:) withObject:cell afterDelay:0.0];

At alignText: you can redefine textLabel/detalTextLabel frames.

See implementation at here

Upvotes: 0

KDaker
KDaker

Reputation: 5909

add your own UILabel as a subview to the cell if you want to customize it:

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.textAlignment = UITextAlignmentRight;
UILabel *subLabel = [UILabel alloc] initWithFrame:CGRectMake(x,y,w,h)]; //put in the frame variables you desire
subLabel.textAlignment = UITextAlignmentRight;
subLabel.tag = 20;
subLabel.text = @"my text";
[cell.contentView addSubview:subLabel];
[subLabel release]; //dont call this if you are using ARC

...

then you access the label later:

[[cell.contentView viewWithTag:20] setText:@"new text"];

hope this helps.

Upvotes: 3

Ravi
Ravi

Reputation: 8309

Did you check if the length of your detailTextLabel is not as big as its frame? If the frame is just big enough to fit the text exactly, then it might look like UITextAlignmentRight isn't working.

Upvotes: 1

Nenad M
Nenad M

Reputation: 3055

Try implementing the tableView:willDisplayCell:forRowAtIndexPath: delegate method and put your re-alignment code there!

Upvotes: 0

Related Questions