Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self sizing cell with multiple labels does not show multiline label

I'm having three labels in my static table view cell and the middle label should be a multiline one.

I'm setting these two lines in viewDidLoad()

self.tableView.estimatedRowHeight = 130.0
self.tableView.rowHeight = UITableViewAutomaticDimension

The storyboard looks like this

enter image description here

Here are the constraints for each subview

Top label, middle label, bottom label, button

enter image description here

I've also set the number of lines for the middle label to 0. However it only shows one single line, instead of multiple lines. I guess it must have something to do with content hugging or content compression priorities or it's because my I'm using a UITableViewController with static cells.

UPDATE

If I change Vertical Compression Resistance Priority of the middle label to 751 and Vertical Content Hugging Priority to 250, the label shows multilines, but the cell does not get resized, so the top and the bottom label are outside the cell now.

UPDATE 2

I've just created a sample project and it turned out that it works with dynamic cells as expected but not with static cells. You can download the sample project here: https://dl.dropboxusercontent.com/u/67692950/ResizingCell.zip

like image 274
gpichler Avatar asked Aug 23 '15 11:08

gpichler


2 Answers

I cloned your sample project. I think the problem is that you don't need to set UITableViewCell's height.

This is the one simple solution.

enter image description here

・To set Row Height "Default" in Table View Cell.(Unchecked Custom)

In this case, it works.

Download the sample project that I implemented here: https://www.dropbox.com/s/w8q6ov9qjfxu1l3/ResizingCell.zip?dl=0

But the other way is that you calculate UITableViewCell's height from UILabel's height.

If you customize cell more complicatedly, it is better to isolate cell as a Custom cell.

like image 168
pixyzehn Avatar answered Nov 15 '22 17:11

pixyzehn


Firstly, open storyboard, set your tableview row height to be 100, uncheck custom row height for the tableview cell, which value is currently 100.

Secondly, like @DBoyer said, call layoutIfNeeded. If you see "Unable to simultaneously satisfy constraints, Will attempt to recover by breaking constraint X", lower X's priority to 999. I think the warnings may have something to do with that when you get the cell, cell frame is CGRectZero.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
    cell.layoutIfNeeded()
    return cell
}
like image 28
gabbler Avatar answered Nov 15 '22 19:11

gabbler