UIStackView programmatically

demo

This project demonstrates how to:

– Create a UIStackView
– add uiviews to it
– add constraints to the uiviews
– make each uiview appear and disappear

stackview_row_result

http://angelolloqui.com/blog/36-Oddities-of-UIStackView
https://developer.apple.com/documentation/uikit/uiview/1622572-translatesautoresizingmaskintoco

Creating a constraint

Say you want to create a constraint. That constraints sits on constraint creation conveniences such as heightAnchor, widthAnchor, topAnchor, leftAnchor, etc. Any property that you can create a constraint on, that property will have an anchor you can access, and thus, create constraints from.

In our case, we want to to set a constraint to our height. Thus there is a heightAnchor. Access that property to create a constraint.

translatesAutoresizingMaskIntoConstraints

From the doc: If you want to use Auto Layout to dynamically calculate the size and position of your view, you must set this property to false, and then provide a non ambiguous, nonconflicting set of constraints for the view.

By default, the property is set to true for any view you programmatically create.

If you add views in Interface Builder, the system automatically sets this property to false.

Resolving Constraint conflicts using priority

Thus, later on we’ll be hiding our viewA. However there is a constraint on viewA that says its height has to be 120, as stated earlier. In this case, we’ll get a constraint conflict in the log console, because setting aView’s isHidden to true, makes its height to 0. This is a constraint conflict with 120.

Thus, in order to fix this, we need to lower the priority of our 120 height constraint so that when viewA’s height changes to 0 (due to it being hidden), it will see that the 120 height constraint’s priority is lower. This is because any new height constraints has a default priority of 1000. Since 120 has a lower priority, then the constraints engine will allow 0 (which defaults to highest priority of 1000) to be valid.

Full Source