Autolayout Extensions September 12, 2016

Writing programatic constraints with NSLayoutAnchors can get wordy. If I want to constrain a view to all four sides of the superview for example, I need to write four lines of code:

             
      self.addConstraint(tableView.topAnchor.constraint(equalTo: self.topAnchor))
      self.addConstraint(tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor))
      self.addConstraint(tableView.leftAnchor.constraint(equalTo: self.leftAnchor))
      self.addConstraint(tableView.rightAnchor.constraint(equalTo: self.rightAnchor))
            
          

This is too common an occurance in a application to rewrite these four lines over and over.

Instead, with an extension to UIView, you can accomplish these constraints with just one line. This follows the DRY (don't repeat yourself) principle, and makes the code much cleaner and easier to maintain.

             
      self.haveViewFilledBy(view)
            
          

The extension provides a group of useful methods like haveViewFilledBy() for common constraints.

            extension UIView {
        func haveViewFilledBy(_ view: UIView) {
            constrainViewToTopBottom(view)
            constrainViewToLeftRightSides(view)
        }
        
        func haveViewFilledWithSpacingBy(_ view: UIView,_ constant: CGFloat) {
            constrainViewToLeftRightSidesWithSpacing(view, constant)
            constrainViewToTopBottomWithSpacing(view, constant)
        }
        
        func constrainViewToLeftRightSides(_ view: UIView) {
            constrainViewToLeftRightSidesWithSpacing(view, 0)
        }
        
        func constrainViewToLeftRightSidesWithSpacing(_ view: UIView,_ constant: CGFloat) {
            self.addConstraint(view.leftAnchor.constraint(equalTo: (view.superview?.leftAnchor)!, constant: constant))
            self.addConstraint(view.rightAnchor.constraint(equalTo: (view.superview?.rightAnchor)!, constant: -constant))
        }
        
        func constrainViewToTopBottom(_ view: UIView) {
            constrainViewToTopBottomWithSpacing(view, 0)
        }
        
        func constrainViewToTopBottomWithSpacing(_ view: UIView,_ constant: CGFloat) {
            self.addConstraint(view.topAnchor.constraint(equalTo: (view.superview?.topAnchor)!, constant: constant))
            self.addConstraint(view.bottomAnchor.constraint(equalTo: (view.superview?.bottomAnchor)!, constant: -constant))
        }
        
        func centerInSuperView(_ view: UIView) {
            self.addConstraint(view.centerXAnchor.constraint(equalTo: (view.superview?.centerXAnchor)!))
            self.addConstraint(view.centerYAnchor.constraint(equalTo: (view.superview?.centerYAnchor)!))
        }
      }
          

That's it! Have fun and #CompileSwift.