Created
April 30, 2021 23:37
-
-
Save bricker/4edecae5e6c083ca6ec7524db7062724 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
import UIKit | |
class ConstraintDSL { | |
private let view: UIView | |
private var chain: [NSLayoutConstraint] = [] | |
init(_ view: UIView) { | |
self.view = view | |
} | |
func centeredX(to parentView: UIView) -> Self { | |
let constraint = view.centerXAnchor.constraint(equalTo: parentView.centerXAnchor) | |
chain.append(constraint) | |
return self | |
} | |
func centeredY(to parentView: UIView) -> Self { | |
let constraint = view.centerYAnchor.constraint(equalTo: parentView.centerYAnchor) | |
chain.append(constraint) | |
return self | |
} | |
func maxWidth(_ constant: CGFloat) -> Self { | |
let constraint = view.widthAnchor.constraint(lessThanOrEqualToConstant: constant) | |
chain.append(constraint) | |
return self | |
} | |
func minWidth(_ constant: CGFloat) -> Self { | |
let constraint = view.widthAnchor.constraint(greaterThanOrEqualToConstant: constant) | |
chain.append(constraint) | |
return self | |
} | |
func minPaddingX(_ constant: CGFloat, from parentView: UIView) -> Self { | |
let constraintL = view.leadingAnchor.constraint(greaterThanOrEqualTo: parentView.leadingAnchor, constant: constant) | |
chain.append(constraintL) | |
let constraintR = view.trailingAnchor.constraint(lessThanOrEqualTo: parentView.trailingAnchor, constant: -constant) | |
chain.append(constraintR) | |
return self | |
} | |
// ... etc | |
func activate() { | |
NSLayoutConstraint.activate(chain) | |
} | |
} |
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
class Controller: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let button = UIButton() | |
// ... configuration | |
ConstraintDSL(button) | |
.centeredX(to: view) | |
.centeredY(to: view) | |
.minWidth(200) | |
.maxWidth(400) | |
.minPaddingX(16, from: view) | |
.activate() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment