Rob N
Rob N

Reputation: 16429

How to stop UILabel from truncating with '...' in UITableCellView

I have two UILabels in a custom table cell, each with "Lines" set to "0" in Interface Builder. They are vertically stacked with left and right edges aligned, inside a table with row height determined by auto layout. But one of them insists on truncating anyway. Why? It should take up needed lines and push out the height of the table cell.

enter image description here

Upvotes: 3

Views: 7770

Answers (4)

john07
john07

Reputation: 560

layoutSubviews for cell and viewDidLayoutSubviews don't work. You needs using custom container view for cell and set preferredMaxLayoutWidth in container layoutSubviews. I have special subclass for UIView

class ExtendedView:UIView{

var didLayoutSubviews:(()->Void)!;

override func layoutSubviews() {
    super.layoutSubviews();
    if let completion = didLayoutSubviews {
        completion();
        layoutIfNeeded();
    }
}

}

using example

container.didLayoutSubviews = {[unowned self] in
    let left =  self.statusLabel.frame.minX - 4;
    width = left - self.title.frame.minX;
    self.title.preferredMaxLayoutWidth = round(width)
    container.layoutIfNeeded()
}

Upvotes: 0

ABakerSmith
ABakerSmith

Reputation: 22939

You need to make sure you set the preferredMaxLayoutWidth of the UILabel. iOS8 is supposed to do this for you but I've also had issues with the end being truncated when having custom dynamic sized UITableViewCells. A workaround for this is to set preferredMaxLayoutWidth, in layoutSubviews, to the width of the label.

Upvotes: 5

batkru
batkru

Reputation: 295

To get automatic cell sizing you need to make sure you have the following (Considering you're using Auto Layout)

  1. Make sure your views have constraints that eventually touch the edges of the cell, in your case, since you just have one label, you can put the top, left, right and bottom spacing to 0 to all edges.
  2. Make sure you set tableView's estimatedRowHeight property to a value, it could be tableView.estimatedRowHeight = 44 for example
  3. Make sure you set tableView's rowHeight property to UITableViewAutomaticDimension on viewDidLoad
  4. Make sure your label has 0 as number of lines

With this, your cells will grow as needed and you should be able to see your labels correctly.

Thanks

Upvotes: 0

Akhil
Akhil

Reputation: 6697

Try calling [cell.textLabel sizeToFit] It will resize the labelview according to its content.

Upvotes: 2

Related Questions