0

Question: How can I use constraints in a UITableViewCell using UITableViewAutomaticDimension when there are labels side by side which can each contain a different number of lines?

I have a table with cells that contain labels side by side:

tablecells with horizontal labels

I'm having a hard time getting the cell to size properly if one of the labels on one side have more lines than the corresponding label on the other side. One of the labels always gets cut off. If both labels have the same number of lines, the cell resizes perfectly and all text can be seen.

I've tried a number of constraint tweaks but nothing is working perfectly as desired.

I've tried adding hidden label for height...but it doesn't work well for the cell with 4 labels I've tried placing the labels in a view but then the height of the view still needs to be calculated.

Currently the constraints are setup normally: top, bottom, left , right, labels are set to 0 lines etc and works great when both labels have the same text or same number of lines.

Is there any way I can do this with constraints? Or do I need to revert to the old height for row at index path? =(

Amos
  • 182
  • 10

2 Answers2

0

I found a solution where I did not have to revert to using tableView:heightForRowAtIndexPath.

I added a label to the cell with the text color set to clearColor and called it 'heightLabel'. I added constraints to the heightLabel so the cell would resize based on the heightLabel's constraints.

Then whichever of the left or right labels had the most text, I placed that label's text inside the heightLabel.

The cells still were not resizing and I had to call 'layoutIfNeeded' on the cell before returning the cell in tableView:cellForRowAtIndexPath.

The heightLabel constraints are now what is being used to resize the cell and UITableViewAutomaticDimensions is working properly.

This may not be the best solution but it's working out pretty well. If there is a more proper way of doing this I'm open to suggestions.

Amos
  • 182
  • 10
0

There is a way to achieve what you want to do just using constraints. The trick is to set the relation of the constraints between the two lower labels and the bottom to Greater Than or Equal instead of equal.

Here is how I set the constraints:

enter image description here

Which has this result:

enter image description here

Or you could set the constraints between the labels top and bottom to Greater Than or Equal and leave the bottom constraint at equal:

enter image description here

To get this result:

enter image description here

joern
  • 27,354
  • 7
  • 90
  • 105