Pin view to super view

When working with constraints in code the native API can be very painful and * to use. Most of the time we end up writing a lot of boiler plate code every time we just want to do something simple as filling a view in its’ superview.

By extending UIView we can work around the boiler plate code for those times when we need the same constraints over and over again:

extension UIView {
    func pinToSuperview(with insets: UIEdgeInsets = .zero, edges: UIRectEdge = .all) {
        // 1
        guard let superview = superview else { return }

        // 2
        translatesAutoresizingMaskIntoConstraints = false

        // 3
        if edges.contains(.top) {
            topAnchor.constraint(equalTo: superview.topAnchor, constant: insets.top).isActive = true
        }

        // 4
        if edges.contains(.bottom) {
            bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: -insets.bottom).isActive = true
        }

        // 5
        if edges.contains(.left) {
            leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: insets.left).isActive = true
        }

        // 6
        if edges.contains(.right) {
            trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: -insets.right).isActive = true
        }
    }
}

Lets go through it.

  1. First check if we have a superview in the first place.
  2. If we haven’t set translatesAutoresizingMaskIntoConstraints to false on our view yet we make sure we do it here so we can work with the constraints.
  3. Check if edges contains top, and if it does we add a top constraint from the superviews’ top anchor with the inset top value and activate it.

Albeit this extension won’t solve all our constraint boiler plate code problems, this is very useful. Now we can fill a view in its’ superview like this:

let view = UIView()
view.pinToSuperview()

And with some edge inset as well:

view.pinToSuperview(with: UIEdgeInsets(top: 10, left: 20, bottom: 30, right: 20))