Skip to content

Instantly share code, notes, and snippets.

@Coder-ACJHP
Created April 5, 2019 08:42
Show Gist options
  • Save Coder-ACJHP/6283d104026639ff763caab524ce8a0f to your computer and use it in GitHub Desktop.
Save Coder-ACJHP/6283d104026639ff763caab524ce8a0f to your computer and use it in GitHub Desktop.
Make autolayout easier with this extension.
extension UIView {
func fillContainer() {
anchor(top: superview?.topAnchor, leading: superview?.leadingAnchor,
bottom: superview?.bottomAnchor, trailing: superview?.trailingAnchor)
}
// When you use this function don't pass "size" parameter into "anchor" function
func anchorSize(to view: UIView) {
widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true
heightAnchor.constraint(equalTo: view.heightAnchor).isActive = true
}
func anchor(top: NSLayoutYAxisAnchor? = nil, leading: NSLayoutXAxisAnchor? = nil,
bottom: NSLayoutYAxisAnchor? = nil, trailing: NSLayoutXAxisAnchor? = nil,
padding: UIEdgeInsets = .zero, size: CGSize = .zero ) {
translatesAutoresizingMaskIntoConstraints = false
if let top = top {
topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true
}
if let leading = leading {
leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true
}
if let bottom = bottom {
bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom).isActive = true
}
if let trailing = trailing {
trailingAnchor.constraint(equalTo: trailing, constant: -padding.right).isActive = true
}
if size.width != 0 {
widthAnchor.constraint(equalToConstant: size.width).isActive = true
}
if size.height != 0 {
heightAnchor.constraint(equalToConstant: size.height).isActive = true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment