Allow pinning to a view with padding

This commit is contained in:
Jed Fox 2022-11-26 09:36:57 -05:00
parent dd95724d14
commit 4014fb41f1
No known key found for this signature in database
GPG Key ID: 0B61D18EA54B47E1
2 changed files with 21 additions and 8 deletions

View File

@ -0,0 +1,14 @@
//
// UIEdgeInsets.swift
//
//
// Created by Jed Fox on 2022-11-24.
//
import UIKit
extension UIEdgeInsets {
public static func constant(_ offset: CGFloat) -> Self {
UIEdgeInsets(top: offset, left: offset, bottom: offset, right: offset)
}
}

View File

@ -48,20 +48,19 @@ extension UIView {
} }
public extension UIView { public extension UIView {
@discardableResult @discardableResult
func pinToParent() -> [NSLayoutConstraint] { func pinToParent(padding: UIEdgeInsets = .zero) -> [NSLayoutConstraint] {
pinTo(to: self.superview) pinTo(to: self.superview, padding: padding)
} }
@discardableResult @discardableResult
func pinTo(to view: UIView?) -> [NSLayoutConstraint] { func pinTo(to view: UIView?, padding: UIEdgeInsets = .zero) -> [NSLayoutConstraint] {
guard let pinToView = view else { return [] } guard let pinToView = view else { return [] }
let constraints = [ let constraints = [
topAnchor.constraint(equalTo: pinToView.topAnchor), topAnchor.constraint(equalTo: pinToView.topAnchor, constant: padding.top),
leadingAnchor.constraint(equalTo: pinToView.leadingAnchor), leadingAnchor.constraint(equalTo: pinToView.leadingAnchor, constant: padding.left),
trailingAnchor.constraint(equalTo: pinToView.trailingAnchor), trailingAnchor.constraint(equalTo: pinToView.trailingAnchor, constant: -padding.right),
bottomAnchor.constraint(equalTo: pinToView.bottomAnchor), bottomAnchor.constraint(equalTo: pinToView.bottomAnchor, constant: -padding.bottom),
] ]
NSLayoutConstraint.activate(constraints) NSLayoutConstraint.activate(constraints)
return constraints return constraints