Skip to content

Instantly share code, notes, and snippets.

@mpospese
Last active November 9, 2019 02:37
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpospese/e5f3a3960770f9e089f9858fa40a58c6 to your computer and use it in GitHub Desktop.
Save mpospese/e5f3a3960770f9e089f9858fa40a58c6 to your computer and use it in GitHub Desktop.
Declarative Auto Layout extension to UIView
import UIKit
extension UIView {
// Declarative Auto Layout helper. Does the same thing as creating a layout constraint but feels more intuitive.
// Also, it remembers to set translatesAutoresizingMaskIntoConstraints = false and allows you to set a constraint's
// priority all in a single method call
// Plus you also don't have to worry about activating the constraint
// Returns: the created constraint in case you wish to hold onto it
@discardableResult public func pin(_ attr1: NSLayoutConstraint.Attribute, to attr2: NSLayoutConstraint.Attribute = .notAnAttribute, of view2: Any? = nil, relatedBy relation: NSLayoutConstraint.Relation = .equal, multiplier: CGFloat = 1, constant c: CGFloat = 0, priority: UILayoutPriority = UILayoutPriority.required, isActive: Bool = true) -> NSLayoutConstraint {
translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint(item: self, attribute: attr1, relatedBy: relation, toItem: view2, attribute: attr2, multiplier: multiplier, constant: c)
constraint.priority = priority
constraint.isActive = isActive
return constraint
}
@discardableResult public func pinEdges(to view2: Any? = nil, withInsets insets: UIEdgeInsets = .zero) -> [NSLayoutConstraint] {
let top = pin(.top, to: .top, of: view2 ?? superview, constant: insets.top)
let leading = pin(.leading, to: .leading, of: view2 ?? superview, constant: insets.left)
let bottom = pin(.bottom, to: .bottom, of: view2 ?? superview, constant: -insets.bottom)
let trailing = pin(.trailing, to: .trailing, of: view2 ?? superview, constant: -insets.right)
return [top, leading, bottom, trailing]
}
@discardableResult public func pinMargins(to view2: Any? = nil, withInsets insets: UIEdgeInsets = .zero) -> [NSLayoutConstraint] {
let top = pin(.topMargin, to: .topMargin, of: view2 ?? superview, constant: insets.top)
let leading = pin(.leadingMargin, to: .leadingMargin, of: view2 ?? superview, constant: insets.left)
let bottom = pin(.bottomMargin, to: .bottomMargin, of: view2 ?? superview, constant: -insets.bottom)
let trailing = pin(.trailingMargin, to: .trailingMargin, of: view2 ?? superview, constant: -insets.right)
return [top, leading, bottom, trailing]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment