Skip to content

Instantly share code, notes, and snippets.

@lacyrhoades
Last active August 27, 2018 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lacyrhoades/366a9c8d86bda2c3e3f033822d35b4cc to your computer and use it in GitHub Desktop.
Save lacyrhoades/366a9c8d86bda2c3e3f033822d35b4cc to your computer and use it in GitHub Desktop.
// viewA is INSIDE OF or a SIBLING OF viewB
let viewA: UIView = ...
let viewB: UIView = ...
// Create constraint like...
let constraint = NSLayoutConstraint(item: viewA, attribute: .height, relatedBy: .equal, toItem: viewB, attribute: .height, multiplier: 1, constant: 0)
// or
let constraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(margin)-[view]-(margin)-|", options: [], metrics: ["margin": 15.0], views: ["view": viewA])
// The visual version above ^^ would break down to essentially this:
[
NSLayoutConstraint(item: viewA, attribute: .top, relatedBy: .equal, toItem: viewB, attribute: .top, multiplier: 1, constant: 15.0)
NSLayoutConstraint(item: viewA, attribute: .bottom, relatedBy: .equal, toItem: viewB, attribute: .bottom, multiplier: 1, constant: 15.0)
]
// Optional: Set priority over similar constraints
constraint.priority = .defaultHigh // or .required, or ...
// Add to some view
aSuperview.addConstraint(constraint)
// If viewB is a superview
viewB.addConstraint(constraint)
// Or
aSuperview.addConstraints(constraints)
// Or let it find out the "superview" for each constraint for you
NSLayoutConstraint.activate([constraint])
// Or ...
NSLayoutConstraint.activate(constraints)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment