Skip to content

Instantly share code, notes, and snippets.

@haojianzong
Last active April 9, 2022 09:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haojianzong/d0118091bd571eb376399cbf6e72a9a7 to your computer and use it in GitHub Desktop.
Save haojianzong/d0118091bd571eb376399cbf6e72a9a7 to your computer and use it in GitHub Desktop.
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)
}
}
@Shinolr
Copy link

Shinolr commented May 18, 2021

Thanks dude. This post UITableViewHeaderFooterContentView's width should equal 0 save my day.

@haojianzong
Copy link
Author

@Shinolr You are welcome! Glad you found the post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment