Created
June 16, 2020 16:25
-
-
Save nekonora/55ef5af5812f49b5600bddb2eda3202d to your computer and use it in GitHub Desktop.
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 | |
extension UIView { | |
func setConstraint(_ constraintBlock: ((UIView) -> Void)) { | |
translatesAutoresizingMaskIntoConstraints = false | |
constraintBlock(self) | |
layoutIfNeeded() | |
} | |
func fillSuperview(padding: Int? = nil) { | |
guard let superview = superview else { return } | |
setConstraint() { | |
$0.top(to: superview.topAnchor, constant: padding ?? 0) | |
$0.bottom(to: superview.bottomAnchor, constant: -(padding ?? 0)) | |
$0.leading(to: superview.leadingAnchor, constant: padding ?? 0) | |
$0.trailing(to: superview.trailingAnchor, constant: -(padding ?? 0)) | |
} | |
} | |
func fillSafeArea(padding: Int? = nil) { | |
guard let superview = superview?.safeAreaLayoutGuide else { return } | |
setConstraint() { | |
$0.top(to: superview.topAnchor, constant: padding ?? 0) | |
$0.bottom(to: superview.bottomAnchor, constant: -(padding ?? 0)) | |
$0.leading(to: superview.leadingAnchor, constant: padding ?? 0) | |
$0.trailing(to: superview.trailingAnchor, constant: -(padding ?? 0)) | |
} | |
} | |
func top(to anchor: NSLayoutYAxisAnchor, constant: Int = 0) { | |
topAnchor.constraint(equalTo: anchor, constant: CGFloat(constant)).isActive = true | |
} | |
func bottom(to anchor: NSLayoutYAxisAnchor, constant: Int = 0) { | |
bottomAnchor.constraint(equalTo: anchor, constant: CGFloat(constant)).isActive = true | |
} | |
func leading(to anchor: NSLayoutXAxisAnchor, constant: Int = 0) { | |
leadingAnchor.constraint(equalTo: anchor, constant: CGFloat(constant)).isActive = true | |
} | |
func trailing(to anchor: NSLayoutXAxisAnchor, constant: Int = 0) { | |
trailingAnchor.constraint(equalTo: anchor, constant: CGFloat(constant)).isActive = true | |
} | |
func centerX(to anchor: NSLayoutXAxisAnchor, constant: Int = 0) { | |
centerXAnchor.constraint(equalTo: anchor, constant: CGFloat(constant)).isActive = true | |
} | |
func centerY(to anchor: NSLayoutYAxisAnchor, constant: Int = 0) { | |
centerYAnchor.constraint(equalTo: anchor, constant: CGFloat(constant)).isActive = true | |
} | |
func width(_ value: Int) { | |
widthAnchor.constraint(equalToConstant: CGFloat(value)).isActive = true | |
} | |
func height(_ value: Int) { | |
heightAnchor.constraint(equalToConstant: CGFloat(value)).isActive = true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment