Created
July 24, 2020 13:17
-
-
Save netgfx/f421dcd76fa08dbc33cf5fe98e0b8d64 to your computer and use it in GitHub Desktop.
UIViewExtension.swift
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
// | |
// UIViewExtensions.swift | |
// | |
// | |
import Foundation | |
import UIKit | |
extension UIView { | |
func anchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, padding: UIEdgeInsets = .zero, size: CGSize = .zero) { | |
translatesAutoresizingMaskIntoConstraints = false | |
if let top = top { | |
self.topAnchor.constraint(equalTo: top, constant: padding.top).isActive = true | |
} | |
if let leading = leading { | |
self.leadingAnchor.constraint(equalTo: leading, constant: padding.left).isActive = true | |
} | |
if let bottom = bottom { | |
self.bottomAnchor.constraint(equalTo: bottom, constant: -padding.bottom).isActive = true | |
} | |
if let trailing = trailing { | |
self.trailingAnchor.constraint(equalTo: trailing, constant: -padding.right).isActive = true | |
} | |
if size.width != 0 { | |
self.widthAnchor.constraint(equalToConstant: size.width).isActive = true | |
} | |
if size.height != 0 { | |
self.heightAnchor.constraint(equalToConstant: size.height).isActive = true | |
} | |
} | |
func fillSuperview(padding: UIEdgeInsets = .zero) { | |
translatesAutoresizingMaskIntoConstraints = false | |
if let superviewTopAnchor = superview?.topAnchor { | |
topAnchor.constraint(equalTo: superviewTopAnchor, constant: padding.top).isActive = true | |
} | |
if let superviewBottomAnchor = superview?.bottomAnchor { | |
bottomAnchor.constraint(equalTo: superviewBottomAnchor, constant: -padding.bottom).isActive = true | |
} | |
if let superviewLeadingAnchor = superview?.leadingAnchor { | |
leadingAnchor.constraint(equalTo: superviewLeadingAnchor, constant: padding.left).isActive = true | |
} | |
if let superviewTrailingAnchor = superview?.trailingAnchor { | |
trailingAnchor.constraint(equalTo: superviewTrailingAnchor, constant: -padding.right).isActive = true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment