annaoomph
annaoomph

Reputation: 572

How to build a layout of single line and multi line labels in iOS autolayout?

I have an application in swift,and have encountered an autolayout issue. I've come up with the solution to it, but it doesn't seem to work as expected.

So, here's the issue: I have two labels in a table view cell. The first one should only have one line, and the second one must have as many lines as needed and take up as much vertical space as needed. The first label should always be shown fully and, therefore, determine the position, the size, and the number of lines of the second label. Texts for both are set programmatically when drawing the cell, of course.

The solution seems to be pretty simple: Anchor the first label to the left, center it vertically, anchor the second label to the parent top, right, bottom and the right side of the first one. Set the number of lines to 0 for the second label. The editor shows no warnings or errors.

This is how it looks like:

Constraints

In most cases it looks good, like on the picture below, but sometimes not (red arrows at the picture below):

Screenshots

The first label should have absolute priority and never be truncated, wrapped, or cut, but this happens. What am I doing wrong?

UPD: For the question to be more clear, the first label is so called 'margin label', it represents the margin and the indicator of the cell. This is done to imitate a tree structure. The second is, of course, the text itself. '>' is for the closed comment, 'v' is for the opened.

Upvotes: 2

Views: 1219

Answers (4)

Rukshan
Rukshan

Reputation: 8066

Increase the content compression resistance priority of the first label. If needed increase the horizontal content hugging priority of the second label.

Upvotes: 0

Fogmeister
Fogmeister

Reputation: 77621

Select the first label (the >) and go into the measurements panel in Interface Builder.

Near the bottom it will have a value for "Content Compression Resistance". Currently it will be 251 or 751 (I can't remember which) and it will be equal to the other label.

Change this value to 1000. This will stop it from compressing and make the second label compress instead.

Upvotes: 3

nerezza
nerezza

Reputation: 393

you can set the trailing of the first label is >= to the leading of the second label

Upvotes: 0

Kazim Ahmad
Kazim Ahmad

Reputation: 15

set height constraint for first label and set 1 for 'lines' attribute

Upvotes: 0

Related Questions