Programmatic AutoLayout in MVVM

How to write AutoLayout constraint programmatically in an MVVM app.

Riccardo Cipolleschi
Nerd For Tech

--

When developing an iOS app with UIKit, we need to decide how to layout our views. The three alternatives are: Storyboard/XIB files, programmatic AutoLayout or manually set up the view’s frames. Among these three, the one that I know less about is programmatic AutoLayout, and I wanted to learn how it works.

From a very high-level perspective, AutoLayout lets us arrange our UI components on the screen by defining a set of constraints in a declarative approach. These constraints are links between two views: a subject view, the view that we want to layout, and a reference view, an anchor to which we want to bind our view.

Once set up, these constraints should be handled automatically by the system. If the device rotates, the view updates itself accordingly. If the anchor view changes size, the subject is moved accordingly.

These constraints are typically drawn in a Storyboard or in a XIB file. These files are visual representations of an XML structure. When committed, these resource files are stored as XML and this brings some limitations, especially when working in teams:

  1. They hide how things actually work. If there is something wrong or a visual bug, it usually takes a lot of time to understand it and fix it using a visual file.
  2. They are versioned as XML with custom syntax. This makes it very hard to collaborate and…

--

--

Riccardo Cipolleschi
Nerd For Tech

Hey there, I’m Riccardo. Software engineer at Meta. I have a passion for iOS and I love to share my knowledge with others.