Skip to content

Instantly share code, notes, and snippets.

@NSAntoine
Created January 8, 2023 16:07
Show Gist options
  • Save NSAntoine/0c0e935a2061d49dde9a5a4e0eca4be7 to your computer and use it in GitHub Desktop.
Save NSAntoine/0c0e935a2061d49dde9a5a4e0eca4be7 to your computer and use it in GitHub Desktop.
//
// BasicLayoutAnchorsHolding.swift
// Watch The Throne
//
// Created by Serena on 07/01/2023
//
import UIKit
/// A protocol describing a type with the basic layout anchors
/// used for constraining a view with `NSLayoutConstraint`
protocol BasicLayoutAnchorsHolding {
var topAnchor: NSLayoutYAxisAnchor { get }
var bottomAnchor: NSLayoutYAxisAnchor { get }
var leadingAnchor: NSLayoutXAxisAnchor { get }
var trailingAnchor: NSLayoutXAxisAnchor { get }
var centerXAnchor: NSLayoutXAxisAnchor { get }
var centerYAnchor: NSLayoutYAxisAnchor { get }
}
extension BasicLayoutAnchorsHolding {
/// Activate constraints to cover the target with the current item.
func constraintCompletely<Target: BasicLayoutAnchorsHolding>(to target: Target) {
NSLayoutConstraint.activate([
leadingAnchor.constraint(equalTo: target.leadingAnchor),
trailingAnchor.constraint(equalTo: target.trailingAnchor),
topAnchor.constraint(equalTo: target.topAnchor),
bottomAnchor.constraint(equalTo: target.bottomAnchor)
])
}
/// Activate constraints to center the target with the current item.
func centerConstraints<Target: BasicLayoutAnchorsHolding>(to target: Target) {
NSLayoutConstraint.activate([
centerXAnchor.constraint(equalTo: target.centerXAnchor),
centerYAnchor.constraint(equalTo: target.centerYAnchor)
])
}
}
extension UIView: BasicLayoutAnchorsHolding {}
extension UILayoutGuide: BasicLayoutAnchorsHolding {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment