Iphone – UITableViewCell – how to make right UILabel truncate instead of left one

iphoneuilabeluitableview

I have created a UITableViewCell using UITableViewCellStyleValue1, which the Apple docs define as:

A style for a cell with a label on the left side of the cell with left-aligned and black text; on the right side is a label that has smaller blue text and is right-aligned. The Settings application uses cells in this style.

I am trying to set the cell text to display some short text on the left, and some long text on the right, e.g.

URL http://www.mylongurl.com/subdirectory/etc

My problem is that the left UILabel gets truncated instead of the right one so it displays as:

U… http://www.mylongurl.com/subdirectory/etc

If I make the URL even longer then BOTH the labels get truncated, e.g.

U… http://www.mylongurl.com…subdirectory/etc

Is there any way to make the right UILabel truncate instead of the left one without using a custom UITableViewCell? I know how to create a custom UITableViewCell, but it seems like overkill?

I can set the UILineBreakMode to change where the text truncates within the UILabel, but I can't see a way to make the detailTextLabel adjust its width to let the textLabel display itself.

[[lCell textLabel] setText:@"URL"];
[[lCell detailTextLabel] setText:@"http://www.mylongurl.com/subdirectory/etc"];
[[lCell detailTextLabel] setLineBreakMode:UILineBreakModeMiddleTruncation];

Best Answer

You have a couple of options.

Probably the closest in spirit to what you seem to be asking for is to muck around with the label frames in your UITableViewDelegate's tableView:willDisplayCell:forRowAtIndexPath:. (Doing cell layout modifications in your UITableViewDataSource's tableView:cellForRowAtIndexPath: won't fly, since UITableViewCells do all their own internal layout work after tableView:cellForRowAtIndexPath:.) You can use NSString's -sizeWithFont: to help figure out the layout requirements for your textLabel.

You can also take different approaches, as you mentioned, such as subclassing UITableViewCell or setting cell.textLabel.adjustsFontSizeToFitWidth = YES.