mike.tihonchik
mike.tihonchik

Reputation: 6933

Dynamic views inside UIStackView

What I would like to achieve, is have two container views that will have two labels inside them. This labels are set dynamically and represent either percent or dollar amount. I also have an image view in between them. What I would like to achieve is "container view - image - container view". The issue i am having is as follows: lets say left container has a percent value (from 0-100) and right container view has a dollar amount (potentially up to millions). What I would like to do is for labels to dynamically size and take least possible space. Here are couple of images to have a better understanding:

This is the problem I am experiencing: percent is a single digit and takes small amount of space, while dollar amount is too long and is either cut off completely of scree, or trunkating

I am using Stack views to space three views. Is this even a correct approach to the problem?

Storyboard

EDIT: This is the end result I am trying to achieve:

end result

Upvotes: 0

Views: 2311

Answers (2)

rob mayoff
rob mayoff

Reputation: 385530

You can do this with a stack view. Here's what you need to do:

  1. Set the content hugging and compression resistance priorities of the image view to a low number like 100. This will let the image view stretch to fill extra space, or shrink to leave more space for the numbers.

  2. Set a minimum width constraint on the image view so it doesn't shrink down to nothing if the numbers are really big. Do this by creating a width constraint on the image view, then editing it to be instead of =.

    Your image view constraints should end up like this:

    image view constraints

  3. Set the content mode of your image view to “Aspect Fit”. This will make it shrink or grow the arrow image as needed to fit in the space available without distorting it:

    arrow content mode

  4. For your labels, set Autoshrink to “Minimum Font Scale” with a value of 0.5 and turn on “Tighten Letter Spacing”. This allows the labels to adjust if there's not enough room to fit everything at full size:

    label settings

Result:

demo screen shot

Upvotes: 4

Rand Richter
Rand Richter

Reputation: 88

Select your StackView and open the Attributes inspector change the distribution to Fill Proportionally. I would also test very large numbers to see how it effects the look of your StackView but if I am understanding correctly this should work.

Upvotes: 0

Related Questions