Auto Layout Programmatically

Today we are going to see how to write constraint programmatically using swift.

In this tutorial we are going to place a label with text “Hello world” in center of page horizontally and vertically in all devices using constraints.

First create label called lblName of type UILabel

var lblName = UILabel()

Then inside your viewcontroller’s viewdidload() method write

override func viewDidLoad() {

To keep viewDidLoad lite, we are going to move our setup in separate method setupName().

fileprivate func setupName(){ 
lblName.text = "Hello world"
//Step 1
lblName.translatesAutoresizingMaskIntoConstraints = false
//Step 2
//Step 3
lblName.centerXAnchor.constraint(equalTo: view.centerXAnchor),
lblName.centerYAnchor.constraint(equalTo: view.centerYAnchor)

That’s it. This will place your lblName in center of screen in any device. You don’t have to go through frames and other non-sense.

It’s same steps for all other objects. Inside NSLayoutConstraint.activate you can add constraint required for the objects.

For any object to be placed in position you need 4 constraints.So add those four constraints inside step3 activate and you are good to go.

If you noticed carefully, in above setupName method, I have set only two not four as I mentioned earlier. This is because centerXAnchor will take care of leading and trailing anchors whereas centerYAnchor will take care of top and bottom anchors.

Yeah, it depends on object we are setting but implicitly those objects should have four constraints inorder to lay view correctly.

Thanks for reading.Please feel to ask if you have any queries.

If you like it, please clap and share.