Last active
April 23, 2020 07:08
-
-
Save trilliwon/b4622b1856a4b0716b2835c5a7eaeb7a to your computer and use it in GitHub Desktop.
constrainToEdges, constrain
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
extension UIView { | |
@discardableResult | |
func constrain(constraints: (UIView) -> [NSLayoutConstraint]) -> [NSLayoutConstraint] { | |
let constraints = constraints(self) | |
self.translatesAutoresizingMaskIntoConstraints = false | |
NSLayoutConstraint.activate(constraints) | |
return constraints | |
} | |
@discardableResult | |
func constrainToEdges(_ inset: UIEdgeInsets = .zero) -> [NSLayoutConstraint] { | |
constrain { | |
guard let superview = $0.superview else { return [] } | |
return [ | |
$0.topAnchor.constraint(equalTo: superview.topAnchor, constant: inset.top), | |
$0.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: inset.left), | |
$0.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: inset.bottom), | |
$0.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: inset.right) | |
] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment