7

I have a list of phone rates, the textLabel is the country/territory and the detailTextLabel is the rate I have to display.

For some strings, the textLabel is too long and the detailTextLabel becomes hidden. Is there a setting to automatically adjust the text with if it's too long?

Here is an example where Central African Republic (Mobile) has this issue:

example

Alexandru Pupsa
  • 1,798
  • 4
  • 21
  • 40

2 Answers2

5

On laying out a cell with UITableViewCellStyle.Value1 style the title label seems to get priority and push the detail label out of view. The solution might be to subclass UITableViewCell and override its layoutSubviews():

    override func layoutSubviews() {
        super.layoutSubviews()

        if let detail = self.detailTextLabel {
            // this will do the actual layout of the detail 
            // label's text, so you can get its width
            detail.sizeToFit() 

            // you might want to find a clever way to calculate this
            // instead of assigning a literal
            let rightMargin: CGFloat = 16

            // adjust the detail's frame
            let detailWidth = rightMargin + detail.frame.size.width
            detail.frame.origin.x = self.frame.size.width - detailWidth
            detail.frame.size.width = detailWidth
            detail.textAlignment = .Left

            // now truncate the title label        
            if let text = self.textLabel {
                if text.frame.origin.x + text.frame.size.width > self.frame.width - detailWidth {
                    text.frame.size.width = self.frame.width - detailWidth - text.frame.origin.x
                }
            }
        }
    }

Note that although detail.textAlignment = .Left we account for detail's width and the actual text ends up aligned to the right.

Dmitry
  • 376
  • 3
  • 15
  • You can account for an accessory type by updating `let detailWidth = rightMargin + detail.frame.size.width` to -> `let detailWidth = rightMargin + detail.frame.size.width + (self.accessoryType != .none ? 20 : 0)` – Alex Haas Sep 16 '16 at 18:03
0

So what you probably need to do is manually fix the width of the textLabel, since by default it takes up the whole width of the cell. To do this, you can do the following:

CGRect textLabelFrame = cell.textLabel.frame;
textLabelFrame.size.width -= DETAIL_LABEL_WIDTH;
cell.textLabel.frame = textLabelFrame;

In your cellForRowAtIndexPath, where DETAIL_LABEL_WIDTH is the width you want for the detailTextLabel. Assuming the label is auto-ellipsizing, which it should be, this will cause the text to add a "..." at the end of the label right before the detail text label if the width is longer than the width you are setting above.

BHendricks
  • 4,423
  • 6
  • 32
  • 59