Skip to content

Instantly share code, notes, and snippets.

@thiagobutignon
Created October 24, 2019 21:38
Show Gist options
  • Save thiagobutignon/f7af919d0ce8401d68b139845bc56bfa to your computer and use it in GitHub Desktop.
Save thiagobutignon/f7af919d0ce8401d68b139845bc56bfa to your computer and use it in GitHub Desktop.
import UIKit
extension UIView {
func anchorSize(height: NSLayoutDimension?, width: NSLayoutDimension?, multiplier: CGFloat) {
if let height = height {
heightAnchor.constraint(equalTo: height, multiplier: multiplier)
}
if let width = width {
widthAnchor.constraint(equalTo: width, multiplier: multiplier)
}
}
func anchorCenter(x: NSLayoutXAxisAnchor?, y: NSLayoutYAxisAnchor?) {
translatesAutoresizingMaskIntoConstraints = false
if let x = x {
centerXAnchor.constraint(equalTo: x).isActive = true
}
if let y = y {
centerYAnchor.constraint(equalTo: y).isActive = true
}
}
func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, 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