Created
November 11, 2018 13:59
-
-
Save christopherkarani/f986f04acb3bafeead9b6e0aee0a2c3a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Dimension { | |
func constraint(equalToConstant c: CGFloat) -> NSLayoutConstraint | |
} | |
protocol Anchor { | |
func constraint(equalTo anchor: Self, constant: CGFloat) -> NSLayoutConstraint | |
func constraint(greaterThanOrEqualTo anchor: Self, constant: CGFloat) -> NSLayoutConstraint | |
func constraint(lessThanOrEqualTo anchor: Self, constant: CGFloat) -> NSLayoutConstraint | |
} | |
extension NSLayoutDimension : Dimension {} | |
struct Layout<A: Anchor> { | |
let anchor: A | |
} | |
struct Ref<D:Dimension> { | |
let dimension: D | |
} | |
extension Ref { | |
func constraint(equalToConstant c: CGFloat) { | |
dimension.constraint(equalToConstant: c).isActive = true | |
} | |
} | |
class LayoutProxy { | |
lazy var leading = place(anchor: view.leadingAnchor) | |
lazy var trailing = place(anchor: view.trailingAnchor) | |
lazy var bottom = place(anchor: view.bottomAnchor) | |
lazy var top = place(anchor: view.topAnchor) | |
lazy var width = place(anchor: view.widthAnchor) | |
lazy var height = place(anchor: view.heightAnchor) | |
lazy var centerX = place(anchor: view.centerXAnchor) | |
lazy var centerY = place(anchor: view.centerYAnchor) | |
lazy var widthConst = dimension(dimension: view.widthAnchor) | |
lazy var heightConst = dimension(dimension: view.heightAnchor) | |
fileprivate let view : UIView | |
fileprivate init(_ view: UIView) { | |
self.view = view | |
} | |
func place<A: Anchor>(anchor: A) -> Layout<A> { | |
return Layout(anchor: anchor) | |
} | |
func dimension<D: Dimension>( dimension: D) -> Ref<D> { | |
return Ref(dimension: dimension) | |
} | |
} | |
extension Layout { | |
func equalTo(_ otherAnchor: A, offsetBy constant: CGFloat = 0) { | |
anchor.constraint(equalTo: otherAnchor, constant: constant).isActive = true | |
} | |
func lessThanOrEqualTo(_ otherAnchor: A, offsetBy constant: CGFloat = 0) { | |
anchor.constraint(lessThanOrEqualTo: otherAnchor, constant: constant).isActive = true | |
} | |
func greaterThanOrEqualTo(_ otherAnchor: A, offsetBy constant: CGFloat = 0) { | |
anchor.constraint(greaterThanOrEqualTo: otherAnchor, constant: constant).isActive = true | |
} | |
} | |
extension UIView { | |
func layout(_ proxy: (LayoutProxy) -> ()) { | |
translatesAutoresizingMaskIntoConstraints = false | |
proxy(LayoutProxy(self)) | |
} | |
} | |
extension NSLayoutAnchor: Anchor {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment