Start a Project

Writing AutoLayout constraints Programmatically

AutoLayout in Swift:

AutoLayout constraints allow us to create views that dynamically adjust to the size and position of all the views in your view hierarchy. It was introduced in iOS6.

Pros and cons for writing Auto Layout constraints in code

Pros

Cons

Writing AutoLayout constraints by using Layout Anchors

We need to set the translatesAutoresizingMaskIntoConstraints to false. This is to prevent the view’s auto-resizing mask to be translated into AutoLayout constraints and affecting your constraints.

Secondly, you need to create an array of constraints. In which you define your constraints:

The above example shows the basics of writing constraints and should be both readable and understandable. However, creates a square and centers in its super view. Similarly, the last line is needed to actually activate the constraints so they make your layout appear as expected.

 

Each UIView comes with a collection of anchor properties that allow you to set up relations between views:

Similarly, each Anchor returns subclasses from NSLayoutAnchor which comes with a few common methods to set relationships. In addition, includes equal to, greater than, and less than or equal to the relationship.

Available layout guides

Each and every UIView comes with few layout guides which can also be used as anchors.

Supporting Right-to-Left languages

You can also use  leadingAnchor and trailingAnchor for leftAnchor and rightAnchor. In conclusion, it will lead to support for Right-to-Left languages to your views. This is mostly important for views like labels in which you want to make sure that they get flipped for Right-to-Left languages.

Thank you for reading this article. If you want to read more articles regarding iOS Development click here or if you want to know more about this topic then follow this link.

Exit mobile version