Skip to content

Instantly share code, notes, and snippets.

@tanner0101
Last active July 25, 2018 11:01
Show Gist options
  • Save tanner0101/3dcab950560aea7ebc8f to your computer and use it in GitHub Desktop.
Save tanner0101/3dcab950560aea7ebc8f to your computer and use it in GitHub Desktop.
Constrain a subview to all the edges of its superview with one line.
/**
UIViewExtensions.swift
Constrain a subview to all the edges of its superview with one line.
<https://gist.github.com/3dcab950560aea7ebc8f.git>
*/
import UIKit
extension UIView {
func constrainToSuperview(superview: UIView) {
self.setTranslatesAutoresizingMaskIntoConstraints(false)
//align to edges of super view
superview.addConstraint(
NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: superview, attribute: .Top, multiplier: 1, constant: 0)
)
superview.addConstraint(
NSLayoutConstraint(item: self, attribute: .Right, relatedBy: .Equal, toItem: superview, attribute: .Right, multiplier: 1, constant: 0)
)
superview.addConstraint(
NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: superview, attribute: .Bottom, multiplier: 1, constant: 0)
)
superview.addConstraint(
NSLayoutConstraint(item: self, attribute: .Left, relatedBy: .Equal, toItem: superview, attribute: .Left, multiplier: 1, constant: 0)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment