Redeem Now
Read More
Read now

Writing AutoLayout constraints Programmatically

Auto Layout in Swift:

The Auto Layout constraints allow us to create views that dynamically adjust to different size classes and positions and it was introduced in iOS6. The constraints will make sure that your views adjust to any size changes without having to manually update frames or positions.

Pros and cons for writing Auto Layout constraints in code



Writing 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 Auto Layout constraints and affecting your constraints.

Now you need to start by creating an array of constraints. In this array, you define your set of constraints:

The above example shows the basics of writing constraints and should be both readable and understandable. It creates a square and centers in its super view. And 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 o set up relations between views:

Each Anchor it returns subclasses from NSLayoutAnchor which comes with a few common methods to set relationships. It includes equal to, greater than, and less than or equal to the relationship.

Available layout guides

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

Supporting Right-to-Left languages

Although it might seem really obvious to just use leftAnchor and rightAnchor, you might want to think about using leadingAnchor and trailingAnchor instead. This 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.

. . .


Add Your Comment

Be the first to comment.

Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again