Skip to content

Instantly share code, notes, and snippets.

@IlijaMihajlovic
Created September 13, 2022 12:02
Show Gist options
  • Save IlijaMihajlovic/9e8ef191a6b44c63bca08e8efcdc1e50 to your computer and use it in GitHub Desktop.
Save IlijaMihajlovic/9e8ef191a6b44c63bca08e8efcdc1e50 to your computer and use it in GitHub Desktop.
Auto Layout Anchor Extension Programmatically
import UIKit
//MARK: - Auto Layout Anchor Extension
extension UIView {
func anchor(top: NSLayoutYAxisAnchor?, bottom: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, trailing: NSLayoutXAxisAnchor?, padding: UIEdgeInsets = .zero, size: CGSize = .zero) {
if let top = top {
topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true
}
if let bottom = bottom {
bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom).isActive = true
}
if let leading = leading {
leadingAnchor.constraint(equalTo: leading, constant: padding.left).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