Last updated on September 25th, 2019⏱ Reading Time: 2 mins
As an iOS developer you already know that one of the tasks in the to-do list of any project is to set and configure constraints for any views and subviews added to it. It’s been proved that constraints can become tricky and end up to a real pain in the… app quite often, but everything is just a matter of understanding and a bit of experience. In truth, constraints are just rules you want to apply over the layout of any graphic elements you have on-screen; those rules regard the position, the size and the visual relationship of the views and subviews, and define a default behaviour of the UI even when the orientation of the devices gets changed.
Constraints can be set in two different general ways: Graphically and programmatically. Most people prefer the graphical way to set the constraints, working directly in the storyboard or XIB files. The big advantage of that option is that it offers immediate visual contact to the views that constraints should apply to, so you just “see and do”. However, and despite the easiness of this method, it’s highly possible to mess things up by setting contradictory constraints that cannot be satisfied simultaneously at runtime. Most of the times Xcode is quite helpful by indicating the misplaced constraints and providing tips on what’s wrong and problematic with the constraints, so you just proceed by fixing and updating your constraints until there are no more conflicts.
On the other hand, the programming way is a different approach to set constraints, and it includes two different options: The use of methods and properties that the UIKit provides for that purpose, and the use of a special formatting language, called Visual Format Language. If you have never worked with any of them, then this post is your opportunity to have your first experience with both. By the end of the tutorial you’ll be able to decide if working with constraints in code level is suitable for you, and which method you prefer to work the most with. Actually, both methods can be combined, and they should be combined, especially if you use the Visual Format Language (which admittedly is handy, but not that flexible sometimes). I’m not getting into more details now, as the following parts are dedicated to that, so any obscured points or second thoughts you might have now will be cleared out along the way.