Skip to content

Instantly share code, notes, and snippets.

@shaps80
Created October 27, 2023 11:27
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/c43fa90964d6b21172a392f7a816f710 to your computer and use it in GitHub Desktop.
Save shaps80/c43fa90964d6b21172a392f7a816f710 to your computer and use it in GitHub Desktop.
Automatically scales the font size in respect to dynamic type size changes.
public extension View {
func font<T: BinaryFloatingPoint>(_ scaled: Scaled<T>) -> some View {
modifier(ScaledFontModifier(metric: scaled.value))
}
}
public struct Scaled<T: BinaryFloatingPoint> {
fileprivate let value: T
public static func scaled(size: T) -> Self {
.init(value: size)
}
}
private struct ScaledFontModifier<T: BinaryFloatingPoint>: ViewModifier {
@ScaledMetric fileprivate var metric: T
func body(content: Content) -> some View {
content.font(.system(size: .init(metric)))
}
}
@shaps80
Copy link
Author

shaps80 commented Oct 27, 2023

Example:

#Preview {
    VStack {
        ForEach(DynamicTypeSize.allCases, id: \.hashValue) { size in
            Text("Auto Scaled")
                .font(.scaled(size: 14))
                .dynamicTypeSize(size)
        }
    }
}

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