Skip to content

Instantly share code, notes, and snippets.

@cjnevin
Created October 23, 2022 00:58
Show Gist options
  • Save cjnevin/17e43453b6139c562c58f5855d022780 to your computer and use it in GitHub Desktop.
Save cjnevin/17e43453b6139c562c58f5855d022780 to your computer and use it in GitHub Desktop.
public protocol Anchorable: AnyObject, ConstraintBuilding {}
extension Anchorable {
func anchor(_ attribute: NSLayoutConstraint.Attribute) -> Anchor {
.init(anchorable: self, attribute: attribute)
}
public var leading: Anchor { anchor(.leading) }
public var trailing: Anchor { anchor(.trailing) }
public var top: Anchor { anchor(.top) }
public var bottom: Anchor { anchor(.bottom) }
}
public struct Anchor {
let anchorable: Anchorable
let attribute: NSLayoutConstraint.Attribute
func constraint(
_ relation: NSLayoutConstraint.Relation,
to anchor: Anchor,
constant: CGFloat = 0,
multiplier: CGFloat = 1
) -> NSLayoutConstraint {
return NSLayoutConstraint(
item: anchorable,
attribute: attribute,
relatedBy: relation,
toItem: anchor.attribute == .notAnAttribute ? nil : anchor.anchorable,
attribute: anchor.attribute,
multiplier: multiplier,
constant: constant
)
}
}
extension UIView: Anchorable {
public var anchorable: Anchorable { self }
public func build(_ anchor: Anchor, constant: CGFloat, multiplier: CGFloat) -> ConstraintBuilder {
.init(anchor: anchor, constant: constant, multiplier: multiplier)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment