Search code examples
iosxcodeautolayoutinterface-builderconstraints

Xcode: constraining varying height UILabels to fixed size container


I’m building an iOS app which includes a quiz. Questions are displayed in the upper portion of the screen (see below). There are always five possible answers. The thing is: the answers are procedurally generated and vary in length, which leads to line breaks in the label sometimes.

This is the current state

Maybe it’s hard to tell from the picture, but the spacing between the first and second and then between the second and third is not the same as I intend it to be.

This is what I had in mind

Essentially, I’d like the top- and bottommost labels to have the same space towards the container. The labels in the middle should all have the same spacing between each other, but should also adapt, if one of the labels gets bigger (when the size of a text is longer than the width and a line break occurs).

To achieve this, I tried the following:

  • Organise the labels as a stack view:

    Nearly worked, the only problem I have here is, that the size of the labels is calculated after the stack view is displayed, which leads to wrong constraints/paddings/margins being applied to the (possibly) longer texts at runtime.

  • Organise the labels with regular constraints

    I tried setting the priority of the constraints for the middle labels lower than that of the top- and bottommost ones, so those would be the ones to resize, if the labels enlarges, but it appears that at runtime one of those is chosen to shrink, whereas the others remain at their default size.

I'd really appreciate if you could help me out, constraints always seem to be a pain in my neck...


Solution

  • Agreed... I think UIStackView works fine, just have to set it up properly.

    Also you may need to call .sizeToFit on the labels when you set the text.

    I put up an example for you - the sizing is not exact, but you should be able to follow the technique...

    https://github.com/DonMag/StackViewFun