Skip to content

Instantly share code, notes, and snippets.

@shaps80
Created October 27, 2023 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaps80/9a4278edc17bee188b8c58300d7474cd to your computer and use it in GitHub Desktop.
Save shaps80/9a4278edc17bee188b8c58300d7474cd to your computer and use it in GitHub Desktop.
Automatically scales the padding value in respect to dynamic type size changes.
import SwiftUI
public extension View {
func padding(_ edges: Edge.Set = .all, scaled length: Length) -> some View {
modifier(PaddingModifier(edges: edges, padding: length.rawValue))
}
func padding(scaled length: Length) -> some View {
modifier(PaddingModifier(edges: .all, padding: length.rawValue))
}
}
private struct PaddingModifier: ViewModifier {
let edges: Edge.Set
@ScaledMetric var padding: CGFloat
func body(content: Content) -> some View {
content.padding(edges, padding)
}
}
public struct Length: RawRepresentable, Codable, Hashable, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, Sendable {
public var rawValue: Double
public init(_ rawValue: Double) {
self.rawValue = rawValue
}
public init(rawValue: Double) {
self.rawValue = rawValue
}
public init(integerLiteral value: Int) {
self.rawValue = .init(value)
}
public init(floatLiteral value: Double) {
self.rawValue = value
}
}
extension Length {
public static func * (lhs: Length, rhs: Length) -> Length {
.init(lhs.rawValue * rhs.rawValue)
}
public static func / (lhs: Length, rhs: Length) -> Length {
.init(lhs.rawValue / rhs.rawValue)
}
public static func + (lhs: Length, rhs: Length) -> Length {
.init(lhs.rawValue + rhs.rawValue)
}
public static func - (lhs: Length, rhs: Length) -> Length {
.init(rawValue: lhs.rawValue - rhs.rawValue)
}
public static func *= (lhs: inout Length, rhs: Length) {
lhs.rawValue *= rhs.rawValue
}
public static func /= (lhs: inout Length, rhs: Length) {
lhs.rawValue /= rhs.rawValue
}
public static func += (lhs: inout Length, rhs: Length) {
lhs.rawValue += rhs.rawValue
}
public static func -= (lhs: inout Length, rhs: Length) {
lhs.rawValue -= rhs.rawValue
}
}
@shaps80
Copy link
Author

shaps80 commented Oct 27, 2023

Demo:

// Introduce semantic values
public extension Length {
    static var small: Self = 8
    static var medium: Self = 12
    static var large: Self = 16
}

Text("Foo").padding(scaled: .medium)

You can even use simple arithmetic (for fine-tuning) or even literal values:

Text("Foo").padding(scaled: .small + .medium) // 20
Text("Bar").padding(scaled: 13)

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