Skip to content

Instantly share code, notes, and snippets.

@Koshimizu-Takehito
Last active January 31, 2021 10:39
Show Gist options
  • Save Koshimizu-Takehito/7ccc81418d205004914012da6e347db9 to your computer and use it in GitHub Desktop.
Save Koshimizu-Takehito/7ccc81418d205004914012da6e347db9 to your computer and use it in GitHub Desktop.
public final class ViewController: UIViewController {
private lazy var myView = MyView()
public override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(myView)
myView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(myView, view) { content, parent in
content.leadingAnchor.constraint(equalTo: parent.leadingAnchor)
content.trailingAnchor.constraint(equalTo: parent.trailingAnchor)
content.topAnchor.constraint(equalTo: parent.safeAreaLayoutGuide.topAnchor)
content.bottomAnchor.constraint(equalTo: parent.bottomAnchor)
}
}
}
public extension NSLayoutConstraint {
static func activate<V1: UIView, V2: UIView>(
_ view1: V1,
_ view2: V2,
@Builder _ builder: (_ view1: Proxy<V1>, _ view2: Proxy<V2>) -> [NSLayoutConstraint]
) {
builder(Proxy(view1), Proxy(view2)).forEach { constraint in
constraint.isActive = true
}
}
@_functionBuilder
struct Builder {
public static func buildBlock(_ disposables: NSLayoutConstraint...) -> [NSLayoutConstraint] {
disposables
}
}
@dynamicMemberLookup
class Proxy<View: UIView> {
private var view: View
init(_ view: View) {
self.view = view
}
public subscript<T: LayoutAnchorType>(dynamicMember keyPath: KeyPath<View, T>) -> T {
view[keyPath: keyPath]
}
public subscript(dynamicMember keyPath: KeyPath<View, UILayoutGuide>) -> UILayoutGuide {
view[keyPath: keyPath]
}
}
}
public protocol LayoutAnchorType {}
extension NSLayoutAnchor: LayoutAnchorType {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment