Custom stackView: an easy way to lay out components


13th January 2020


2 min


Carl Sanders

With the recent introduction of a wide range of new components to iOS‚ UIStackView caught my eye. After building a few test apps and deliberating at length with colleagues I realised a core concept I had assumed to be in place was missing – the ability to set specific widths to any ‘Sub views’ placed within a single UIStackView. 

If a stack view only has two sub views everything will layout perfectly; you can set a specific width or height to lone view and set the stack view to equal fill. The issue comes into play when you have more than two sub views – You are unable to set view 1 to be 50 px‚ and view 2 and view 3 to fill equally the rest of the available space without putting a stack view within a stack view. 

So I created my own custom stack view that takes the basic components of a stack view with the added ability to set the size percentage to each object within my ‘CSStackView’.

[object Object]

Figure one

Figure one shows the structure of my CSStackView. After changing a UIView to CSStackView‚ you only need to apply constraints to that; all sub views’ constraints are set programmatically.

[object Object]

Figure two

In my custom class I created an enum of preferred orientation and a variable of percentages. The ‘if’ statement in figure two is a safeguard in case the uses don’t define the amount of % space each sub view has. This counts the amount of sub views and give equal space.

The ‘switch’ statement allows the user to pass which orientation they would like the sub view to be (horizontal or vertical)‚ then loops through each sub view passing the given percentage and applying a new X‚ Y position to the next sub view so they sit side by side with one another.

[object Object]

Figure three

Figure three shows the mainVC and how it’s set up. Simply create an outlet of the customView and apply the percentages of each subView and orientation. As shown in Figure one‚ two of the sub views are of type ‘ViewWithControl’ – this is another customClass that applies the bounds of its child to be the same as the child’s parent.  Figure four shows the end result.

[object Object]