Created
September 13, 2022 12:02
-
-
Save IlijaMihajlovic/9e8ef191a6b44c63bca08e8efcdc1e50 to your computer and use it in GitHub Desktop.
Auto Layout Anchor Extension Programmatically
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 | |
//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