Set Width and Height Constraints of Arranged Subview in UIStackView [Swift]
I use auto-layout a lot. Most of my UI located in Storyboards and XIBs. Storyboards used for definition of general flow and UI containers like UITableView, UIStackView and others. XIBs contain designed views.
This approach causes a problem. If view created in code and added into auto-layout then all or some of its relations and size constraints controlled by container. Rest of them need to be set manually.
In many places I use UIScrollView + UIStackView to manage small dynamic collections of views (which does not care about reuse). Location, relation to other views and one of size constraints controlled by UIStackView.
In my case I need to set only constraint in the code, but many times for different views. It is not reasonable to include BIG but powerful framework into the project.
I wrote small extension to UIView which helps with height and width constraints.
Usage:
let view = UIView()
view.height(constant: 100)
stackView.addArrangedSubview(view)
Code available on GitHub as gist
If you prefer chaining then modification to the code are fairly simple
Don’t forget to subscribe to my Mobile Development Digest with tons of useful articles and frameworks delivered to yours email every Monday. Get fresh digest by email on every Monday
Originally posted at Mobile Development Digest blog