Created
October 27, 2023 11:31
-
-
Save shaps80/9a4278edc17bee188b8c58300d7474cd to your computer and use it in GitHub Desktop.
Automatically scales the padding value in respect to dynamic type size changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo:
You can even use simple arithmetic (for fine-tuning) or even literal values: