Auto Layout extension in Swift (Programmatically)

Sujal Shrestha
2 min readSep 21, 2018

There are lot of ways you can use auto layout anchors in Swift. If you’re using Storyboard, you can anchor your constraints directly from it. But if you want to do it programmatically; things get hectic and redundant. Check the example below for auto layout constraints programatically:

titleLabel.translatesAutoresizingMaskIntoConstraints = falseview.addSubview(titleLabel)titleLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 10).isActive = truetitleLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 10).isActive = truetitleLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: 10).isActive = truetitleLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true

As you can see there are lot of redundancy in the above lines — you’ve to add translatesAutoresizingMaskIntoConstraints, and then you have to make all the constraints active. You can also use NSLayoutConstraint, but it doesn’t make your code look good. Likewise, there are various other external libraries you can integrate in your project for autolayout commands.

One simple solution I have found and was used by Brian Voong (www.letsbuildthatapp.com), is to make a simple custom Extension as follows:

extension UIView {func anchor(top: NSLayoutYAxisAnchor?, paddingTop: CGFloat, bottom: NSLayoutYAxisAnchor?, paddingBottom: CGFloat, left: NSLayoutXAxisAnchor?, paddingLeft: CGFloat, right: NSLayoutXAxisAnchor?, paddingRight: CGFloat, width: CGFloat, height: CGFloat) {translatesAutoresizingMaskIntoConstraints = falseif let top = top {topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true}if let bottom = bottom {bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true}if let right = right {rightAnchor.constraint(equalTo: right, constant: -paddingRight).isActive = true}if let left = left {leftAnchor.constraint(equalTo: left, constant: paddingLeft).isActive = true}if width != 0 {widthAnchor.constraint(equalToConstant: width).isActive = true}if height != 0 {heightAnchor.constraint(equalToConstant: height).isActive = true}}}

That’s it!! That’s all you need! Now you can write your autolayout constriant as follows:

titleLabel.anchor(top: view.topAnchor, paddingTop: 10, bottom: nil, paddingBottom: 0, left: view.leftAnchor, paddingLeft: 10, right: view.rightAnchor, paddingRight: 10, width: 0, height: 50)

As simple as that! Now, you don’t have to bother about translatesAutoresizingMaskIntoConstraints and activating each of your constraints. Similarly, its more readable and concise. Hope you like it :)

--

--