Skip to content

Instantly share code, notes, and snippets.

@chrisbrandow
Created March 26, 2018 19:01
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 chrisbrandow/b3aa5c03c506873c0983d57485eb8215 to your computer and use it in GitHub Desktop.
Save chrisbrandow/b3aa5c03c506873c0983d57485eb8215 to your computer and use it in GitHub Desktop.
Eidhof's Autolayout DSL with a couple additions
typealias Constraint = (_ child: UIView, _ parent: UIView) -> NSLayoutConstraint
func equal<Axis, Anchor>(_ keyPath: KeyPath<UIView, Anchor>, _ to: KeyPath<UIView, Anchor>, _ constant: CGFloat = 0) -> Constraint where Anchor: NSLayoutAnchor<Axis> {
return { $0[keyPath: keyPath].constraint(equalTo: $1[keyPath: to], constant: constant) }
}
func equal<Axis, Anchor>(_ keyPath: KeyPath<UIView, Anchor>, _ constant: CGFloat = 0) -> Constraint where Anchor: NSLayoutAnchor<Axis> {
return equal(keyPath, keyPath, constant)
}
func ==<Axis, Anchor>(_ left: KeyPath<UIView, Anchor>, _ right: KeyPath<UIView, Anchor>) -> Constraint where Anchor: NSLayoutAnchor<Axis> {
return equal(left, right)
}
////////////////////
extension UIView {
func addSubview(_ child: UIView, constraints: [Constraint]) {
addSubview(child)
child.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(constraints.map { $0(child, self) })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment