Carl Sanders, hedgehog lab, on Custom StackView: An Easy Way to Lay Out Components

Partner Post - hedgehog lab - A leading global enterprise app developer

Posted: April 4, 2017


This post was originally featured on hedgehog lab’s blog here. 


Carl Sanders has been developing iOS apps for about 2 years, and has a FdSc Software Applications foundation degree. Main interests are music and new technologies.

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’.

 Figure one

figure 1.png


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.

Figure two

figure 2.png

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.

Figure three

figure 3.png

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.

Figure four

figure 4.png                                                                 

For more, check out the official hedgehog lab site.