A missing Auto Layout helper for UIKit
import Foundation | |
import UIKit | |
// A small utility for NSLayoutDimension shortcuts | |
public protocol PinObject { | |
var topAnchor: NSLayoutYAxisAnchor { get } | |
var bottomAnchor: NSLayoutYAxisAnchor { get } | |
var leadingAnchor: NSLayoutXAxisAnchor { get } | |
var trailingAnchor: NSLayoutXAxisAnchor { get } | |
} | |
extension UIView: PinObject {} | |
extension UILayoutGuide: PinObject {} | |
public extension UIView { | |
struct PinOptions: OptionSet { | |
public let rawValue: Int | |
public static let all: PinOptions = [.top, .trailing, .bottom, .leading] | |
public static let top = PinOptions(rawValue: 1 << 0) | |
public static let trailing = PinOptions(rawValue: 1 << 1) | |
public static let bottom = PinOptions(rawValue: 1 << 2) | |
public static let leading = PinOptions(rawValue: 1 << 3) | |
public init(rawValue: Int) { | |
self.rawValue = rawValue | |
} | |
} | |
func pin(to pinObject: PinObject, edges: PinOptions, priority: UILayoutPriority) { | |
translatesAutoresizingMaskIntoConstraints = false | |
var constraints = [NSLayoutConstraint]() | |
if edges.contains(.leading) { | |
constraints.append(leadingAnchor.constraint(equalTo: pinObject.leadingAnchor)) | |
} | |
if edges.contains(.trailing) { | |
constraints.append(trailingAnchor.constraint(equalTo: pinObject.trailingAnchor)) | |
} | |
if edges.contains(.top) { | |
constraints.append(topAnchor.constraint(equalTo: pinObject.topAnchor)) | |
} | |
if edges.contains(.bottom) { | |
constraints.append(bottomAnchor.constraint(equalTo: pinObject.bottomAnchor)) | |
} | |
constraints.forEach { $0.priority = priority } | |
if !constraints.isEmpty { | |
NSLayoutConstraint.activate(constraints) | |
} | |
} | |
func pinEdges(to parentView: UIView, edges: PinOptions = .all, priority: UILayoutPriority = .required) { | |
pin(to: parentView, edges: edges, priority: priority) | |
} | |
func pinToMargins(of parentView: UIView, edges: PinOptions = .all, priority: UILayoutPriority = .required) { | |
pin(to: parentView.layoutMarginsGuide, edges: edges, priority: priority) | |
} | |
func pinToSafeArea(of parentView: UIView, edges: PinOptions = .all, priority: UILayoutPriority = .required) { | |
pin(to: parentView.safeAreaLayoutGuide, edges: edges, priority: priority) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment