Skip to content

Instantly share code, notes, and snippets.

@cjnevin
Created October 23, 2022 01:03
Show Gist options
  • Save cjnevin/54ac31830edf1503c31882b5d00920e5 to your computer and use it in GitHub Desktop.
Save cjnevin/54ac31830edf1503c31882b5d00920e5 to your computer and use it in GitHub Desktop.
public struct ConstraintBuilder: ConstraintBuilding {
public let anchorable: Anchorable
private let superviewBlock: (NSLayoutConstraint.Relation) -> [NSLayoutConstraint]
public func build(_ anchor: Anchor, constant: CGFloat, multiplier: CGFloat) -> ConstraintBuilder {
combine(with: anchorable.build(anchor, constant: constant, multiplier: multiplier))
}
public func equalToSuperview() -> [NSLayoutConstraint] {
superviewBlock(.equal)
}
public func combine(with other: ConstraintBuilder) -> ConstraintBuilder {
assert(anchorable === other.anchorable)
return ConstraintBuilder(
anchorable: anchorable,
superviewBlock: {
superviewBlock($0) + other.superviewBlock($0)
}
)
}
}
extension ConstraintBuilder {
public init(
anchor lhs: Anchor,
constant: CGFloat = 0,
multiplier: CGFloat = 1
) {
var uiView: UIView? { lhs.anchorable as? UIView }
var superview: UIView? { uiView?.superview }
superviewBlock = { relation in
superview.map { rhs in
[
lhs.constraint(
relation,
to: .init(anchorable: rhs, attribute: lhs.attribute),
constant: constant,
multiplier: multiplier
)
]
} ?? []
}
self.anchorable = lhs.anchorable
uiView?.translatesAutoresizingMaskIntoConstraints = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment