iOS : Weight assignment in Stack view…Percentage-wise size calculation.

Jasmine Elamblakatt
4 min readAug 12, 2019

--

Android layout weight assignment in Linear Layout is a strong feature in layout designing. But the same feature is a little different in iOS. Let's check how can we assign weight or percentage-wise size(height/width) allocation in Stack view.

iOS has varied device sizes, e.g. iPhone SE, iPad, iPhone XS Max device have different sizes.

When we give a fixed size to view it sometimes looks improper in different devices

Check below sample.

E.g.: For below screen in iPhone SE and iPad, iPad Label1 and Label2 are looking very small.

Image of iPad
Image of iPhone SE

The above problem can be solved, if we provide percentage-wise width to labels, then it would display properly in any device size

Suppose we want Label1 and Label2 to be 20% each of the Stackview and Label3 to be 60% of the Stackview.

Check below step:

  1. Select Label1 and parent Stackview and select “Equal Widths” option.

2. Then assign 0.2(20 %) multiplier to Label1 w.r.t superview

3. Then Select Label2 and Stackview and select “Equal Widths” option.

4. Then again assign 0.2(20 %) multiplier to Label2 w.r.t Stackview same as in Label1.

5. Then select Label3 and Stackview add “Equal Widths” constraint and assign 0.6(60%) multiplier w.r.t Superview.

Now check in different screen sizes, the UI will look proper irrespective of screen size.

iPad screen after applying “Equal Width” constraints

Another way to achieve perfect size distribution is through the property “Aspect ratio”

Aspect Ratio is used the control the width and height as per the ratio you specify. If we need to maintain an aspect ratio for the view sizes, then we can use this constraint.

Check below steps:

  1. Select all the child views and add “Aspect Ratio” property

2. Now add width and height based on Stackview size.

Superview(Stackview) width is 375, we will have to divide and assign a width to each label based on the requirement(Label1 - 20%, Label2 - 20%, Label3 - 60%) and we require height to be constant 20

Label1 will be 75:20 (75(20%) will be the width and 20 will be height)

Label2 will be 75:20 (75(20%) will be the width and 20 will be height)

Label3 can be 225:20 (225(60%) will be the width and 20 will be height)

Note: Making width 75:20(20 %) means we want our width to be 20% of the Superview width.

Now if you open the simulator in both iPad, iPhone SE, etc, you’ll always have the Label1 and Label2 taking up 20% and Label 3 taking up 60% of the parent view.

The width will adjust based on the screen size. Same can be done for height also.

iPad screen
iPhone SE screen

Thank you for reading.🙏 If this post helped you, do clap for me 😃

HaPpY CoDiNg….

--

--

Jasmine Elamblakatt
Jasmine Elamblakatt

Written by Jasmine Elamblakatt

Developer(Android, iOS, React Native)

No responses yet