AutoLayout in iOS

Mr.Javed Multani
2 min readOct 3, 2020

Auto Layout dynamically calculates the size and position of all the views in your view hierarchy, based on constraints placed on those views.

Space Views Evenly

It is common to want two views to be side by side, centered in their superview. The common answer given on Stack Overflow is to embed these two views in a UIView and center the UIView. This is not necessary or recommended. From the UILayoutGuide.

There are a number of costs associated with adding dummy views to your view hierarchy. First, there is the cost of creating and maintaining the view itself. Second, the dummy view is a full member of the view hierarchy, which means that it adds overhead to every task the hierarchy performs. Worst of all, the invisible dummy view can intercept messages that are intended for other views, causing problems that are very difficult to find.

You can use UILayoutGuide to do this, instead of adding the buttons into an unnecessary UIView. A UILayoutGuide is essentially a rectangular space that can interact with Auto Layout. You put a UILayoutGuide on the left and right sides of the buttons and set their widths to be equal. This will center the buttons. Here is how to do it in code:

Visual Format Language style

view.addSubview(button2)let leftSpace = UILayoutGuide()
view.addLayoutGuide(leftSpace)let rightSpace = UILayoutGuide()
view.addLayoutGuide(rightSpace)let views = [
"leftSpace" : leftSpace,
"button1" : button1,
"button2" : button2,
"rightSpace" : rightSpace]// Lay the buttons and layout guides out horizontally in a line.
// Put the layout guides on each end. NSLayoutConstraint.activateConstraints(NSLayoutConstraint.constraintsWithVisualFormat(“H:|[leftSpac e][button1]-[button2][rightSpace]|”, options: [], metrics: nil, views: views))// Now set the layout guides widths equal, so that the space on the
// left and the right of the buttons will be equal leftSpace.widthAnchor.constraintEqualToAnchor(rightSpace.widthAnchor).active = true

Anchor Style

let leadingSpace = UILayoutGuide()
let trailingSpace = UILayoutGuide()
view.addLayoutGuide(trailingSpace)leadingSpace.widthAnchor.constraintEqualToAnchor(trailingSpace.widthAnchor).active = true
leadingSpace.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor).active = trueleadingSpace.trailingAnchor.constraintEqualToAnchor(button1.leadingAnchor).active =…
Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer